<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init-pages.php');

$ci = $client_info ?? [];
$br = $branding ?? [];
$wa = $ci['whatsapp'] ?? ['display' => 'N/A', 'link' => '#'];

// Configuración Visual
$google_font_url = $google_font_url ?? '';
$logo_url = $ci['logo_url'] ?? '';
$full_title = $br['full_title'] ?? '';
$favicon = $br['favicon'] ?? '';

// Configuración WhatsApp
$whatsapp_contact = $wa['display'] ?? ''; 
$whatsapp_url_link = $wa['link'] ?? ''; 

// FIX: Validación para evitar el error "Cannot redeclare"
if (!function_exists('formatUSPhoneNumber')) {
    function formatUSPhoneNumber($number) {
        $number = preg_replace('/[^0-9]/', '', $number);
        if (strlen($number) === 10) {
            return '(' . substr($number, 0, 3) . ') ' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
        }
        return $number;
    }
}

// FUNCIÓN PARA FORMATO 24H A 12H 
function convertTo12h($time24) {
    if (empty($time24) || $time24 === '00:00') return 'N/A';
    $time = DateTime::createFromFormat('H:i', $time24);
    if ($time === false) return $time24; 
    return $time->format('g:i A');
}

$whatsapp_display_formatted = formatUSPhoneNumber($whatsapp_contact);
$phone_primary = $ci['phone_primary'] ?? ''; 

// 3. Lógica de Verificación (Sanitización de Input) 
$public_id = $_GET['id'] ?? '';
$public_id = trim(preg_replace('/[^a-zA-Z0-9-]/', '', $public_id)); 
$view_state = 'not_found';
$staff = null;
$schedule_display = "No Schedule Defined"; 
$schedule_details = []; 

// Mensaje por defecto (Genérico, por si no se encuentra el ID)
$wa_message = "Hi! I have a question about a staff member verification.";

if (!empty($public_id) && isset($pdo)) {
    try {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Consulta a la tabla 'staff' usando 'public_uid'
        $stmt = $pdo->prepare("SELECT * FROM staff WHERE public_uid = ? LIMIT 1");
        $stmt->execute([$public_id]);
        $staff = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($staff) {
            
            // A. Foto de Perfil
            $staffFn = htmlspecialchars($staff['first_name'] ?? '');
            $staffLn = htmlspecialchars($staff['last_name'] ?? '');
            $fullName = $staffFn . ' ' . $staffLn;

            // CORRECCIÓN: Mensaje Personalizado con Nombre y ID
            $wa_message = "Hi! I have a question about staff member {$fullName} (ID: {$public_id}).";

            if (empty($staff['profile_photo_url'])) {
                $avatar_name = urlencode($fullName);
                $staff['photo_display'] = "https://ui-avatars.com/api/?name={$avatar_name}&background=07162d&color=fff&size=512&bold=true";
            } else {
                $staff['photo_display'] = htmlspecialchars($staff['profile_photo_url']);
            }
            
            // B. Cálculo de Antigüedad
            $dateSource = !empty($staff['hired_date']) ? $staff['hired_date'] : $staff['created_at'];
            $startDate = new DateTime($dateSource);
            $now = new DateTime();
            $interval = $startDate->diff($now);
            
            if ($interval->y > 0) {
                $tenureText = $interval->y . " Year" . ($interval->y > 1 ? 's' : '');
                if ($interval->m > 0) $tenureText .= ", " . $interval->m . " Month" . ($interval->m > 1 ? 's' : '');
            } elseif ($interval->m > 0) {
                $tenureText = $interval->m . " Month" . ($interval->m > 1 ? 's' : '');
            } else {
                $tenureText = "New Member";
            }
            $staff['tenure_display'] = $tenureText;
            $staff['display_start_date'] = $startDate->format('M Y');

            // C. Horarios
            $days_map = [
                'Mon' => 'Mon', 'Tue' => 'Tue', 'Wed' => 'Wed', 
                'Thu' => 'Thu', 'Fri' => 'Fri', 'Sat' => 'Sat', 'Sun' => 'Sun'
            ];
            $config = json_decode($staff['schedule_config'] ?? '{}', true);
            
            $active_days_list = []; 
            
            foreach ($days_map as $key => $label) {
                if (isset($config[$key]) && !empty($config[$key]['active'])) {
                    $start_time = $config[$key]['start'] ?? '00:00';
                    $end_time = $config[$key]['end'] ?? '00:00';
                    
                    $schedule_details[] = [
                        'day' => $label,
                        'start' => $start_time,
                        'end' => $end_time,
                        'display' => convertTo12h($start_time) . ' - ' . convertTo12h($end_time)
                    ];
                    $active_days_list[] = $label;
                }
            }
            $schedule_display = !empty($active_days_list) ? implode(', ', $active_days_list) : 'Flexible / On Call';


            // D. Determinar Estado Visual y Status
            if ($staff['status'] === 'inactive' || $staff['status'] === 'inactivo') {
                $view_state = 'inactive'; 
            } else {
                // Verificar si está TRABAJANDO AHORA (Clocked In)
                $stmtLog = $pdo->prepare("SELECT id FROM work_logs WHERE staff_id = ? AND clock_out IS NULL ORDER BY id DESC LIMIT 1");
                $stmtLog->execute([$staff['id']]);
                $is_working = $stmtLog->fetchColumn();

                if ($is_working) {
                    $view_state = 'verified'; 
                } else {
                    $view_state = 'off_duty'; 
                }
            }
        }
    } catch (PDOException $e) {
        error_log("STAFF VERIFY ERROR: " . $e->getMessage());
    }
}

if (ob_get_level() > 0) ob_end_clean();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Staff Verification - <?php echo htmlspecialchars($ci['business_name'] ?? 'FlowCRM'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($favicon); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($favicon); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">
    
    <link rel="stylesheet" href="style.css">
    <script src="https://unpkg.com/lucide@latest"></script>

    <style>
        .pulse-green { animation: pulse-green 2s infinite; }
        @keyframes pulse-green {
            0% { box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7); }
            70% { box-shadow: 0 0 0 15px rgba(34, 197, 94, 0); }
            100% { box-shadow: 0 0 0 0 rgba(34, 197, 94, 0); }
        }
        
        .watermark {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 4rem;
            font-weight: 900;
            color: rgba(158, 20, 40, 0.1);
            pointer-events: none;
            z-index: 0;
            white-space: nowrap;
            border: 4px solid rgba(158, 20, 40, 0.1);
            padding: 10px 40px;
            border-radius: 20px;
        }
    </style>
</head>

<body class="max-w-full mx-auto bg-[var(--color-background)]">
    <div id="toast-container" class="toast-container"></div>
    
<header class="bg-white shadow-sm top-0 z-20 border-b-4 border-[var(--color-highlight)]">
    <div class="max-w-6xl mx-auto px-4 py-4 flex flex-col md:flex-row justify-between items-center space-y-3 md:space-y-0">
        
        <div class="flex-shrink-0 flex items-center justify-center">
            <?php if (!empty($biz['logo_url'])): ?>
                <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="h-20 md:h-12 object-contain">
            <?php else: ?>
                <h2 class="text-2xl font-black text-[var(--color-primary)] uppercase">
                    <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
                </h2>
            <?php endif; ?>
        </div>

        <?php 
        $wa_clean = preg_replace('/[^0-9]/', '', $biz['whatsapp'] ?? '');
        // El mensaje ahora se define dinámicamente arriba en PHP
        
        if (!empty($biz['whatsapp'])): 
        ?>
            <a href="https://wa.me/<?php echo $wa_clean; ?>?text=<?php echo rawurlencode($wa_message); ?>" 
               target="_blank" 
               class="flex items-center justify-center space-x-2 bg-green-500 hover:bg-green-600 text-white font-black px-4 py-2 rounded-lg transition-colors shadow-md w-full md:w-auto order-3 md:order-none">
                <i data-lucide="message-circle" class="w-5 h-5"></i>
                <span class="text-lg">WHATSAPP: <?php echo formatUSPhoneNumber($biz['whatsapp']); ?></span>
            </a>
        <?php endif; ?>

        <div class="hidden md:block flex-shrink-0 text-right">
            <h1 class="text-2xl md:text-3xl font-black text-[var(--color-primary)] leading-none">
                <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
            </h1>
            <div class="flex items-center justify-end gap-2 text-[var(--color-secondary)]">
                <i data-lucide="shield-check" class="w-5 h-5"></i>
                <p class="text-sm font-black uppercase tracking-wide">Staff Team Verification System</p>
            </div>
        </div>
        
    </div>
</header>

<main class="max-w-3xl mx-auto px-4 py-8">

    <?php if ($view_state === 'verified'): ?>
        <section class="w-full bg-white rounded-2xl shadow-xl overflow-hidden border-t-8 border-green-500 relative">
            
            <div class="h-28 bg-[var(--color-primary)] relative">
                <div class="absolute inset-0 opacity-10 bg-[radial-gradient(circle,_#ffffff_1px,_transparent_1px)] bg-[length:10px_10px]"></div>
            </div>

            <div class="px-6 pb-8 relative -mt-14 text-center">
                <div class="relative inline-block mb-4">
                    <div class="absolute inset-0 rounded-full pulse-green"></div>
                    <img src="<?php echo htmlspecialchars($staff['photo_display']); ?>" class="w-32 h-32 rounded-full object-cover border-4 border-white shadow-lg relative z-10 bg-gray-100" alt="Staff Photo: <?php echo $staffFn . ' ' . $staffLn; ?>">
                    <div class="absolute bottom-1 right-1 z-20 bg-green-500 text-white p-1.5 rounded-full border-2 border-white shadow-sm" title="Verified">
                        <i data-lucide="shield-check" class="w-5 h-5"></i>
                    </div>
                </div>

                <?php if (!empty($staff['is_employee_of_month'])): ?>
                    <div class="mb-4">
                        <span class="inline-flex items-center gap-1.5 bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest border border-yellow-200 shadow-sm">
                            <i data-lucide="trophy" class="w-3 h-3 text-yellow-600"></i> Employee of the Month
                        </span>
                    </div>
                <?php endif; ?>

                <h1 class="text-3xl font-black text-[var(--color-primary)] uppercase leading-none mb-1">
                    <?php echo htmlspecialchars($staff['first_name'] . ' ' . $staff['last_name']); ?>
                </h1>
                <p class="text-sm font-bold text-[var(--color-secondary)] uppercase tracking-wide mb-4">
                    <?php echo htmlspecialchars($staff['job_title']); ?>
                </p>

                <div class="bg-green-600 border border-green-100 text-white px-4 py-2 rounded-lg text-lg font-black uppercase inline-flex items-center gap-2 mb-6">
                    <span class="relative flex h-2.5 w-2.5">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500"></span>
                    </span>
                    On Duty / Clocked In
                </div>

                <div class="grid grid-cols-2 gap-px bg-gray-100 rounded-lg overflow-hidden border border-gray-200">
                    <div class="bg-white p-3">
                        <p class="text-md text-gray-400 font-black uppercase">Staff ID</p>
                        <p class="text-lg font-bold text-gray-800">#<?php echo htmlspecialchars($staff['public_uid']); ?></p>
                    </div>
                    <div class="bg-white p-3">
                        <p class="text-md text-gray-400 font-black uppercase">Since</p>
                        <p class="text-lg font-bold text-gray-800"><?php echo htmlspecialchars($staff['display_start_date']); ?></p>
                    </div>
                </div>
                
                <div class="mt-2 text-lg text-gray-400 font-black">
                    Exp: <?php echo htmlspecialchars($staff['tenure_display']); ?>
                </div>

                <div class="mt-6 pt-4 border-t border-dashed border-gray-200">
                    <p class="text-2xl font-black text-[var(--color-primary)] uppercase mb-3">Authorized Work Schedule</p>
                    
                    <?php if (empty($schedule_details)): ?>
                        <div class="bg-gray-100 p-3 rounded-lg border border-gray-300 mx-auto w-full max-w-xs">
                            <p class="text-xs font-black text-gray-500 uppercase">NO SCHEDULE DEFINED</p>
                            <p class="text-sm font-extrabold text-[var(--color-secondary)]">NOT AVAILABLE</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-2 text-left w-full max-w-xs mx-auto">
                            <?php foreach($schedule_details as $item): ?>
                                <div class="bg-gray-50 p-2.5 rounded-lg border border-gray-200 flex justify-between items-center">
                                    <span class="text-xs font-black text-gray-700 uppercase w-1/4">
                                        <?php echo htmlspecialchars($item['day']); ?>
                                    </span>
                                    <span class="text-sm font-extrabold text-[var(--color-primary)] whitespace-nowrap">
                                        <?php echo htmlspecialchars($item['display']); ?>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>

    <?php elseif ($view_state === 'off_duty'): ?>
        <section class="w-full bg-white rounded-2xl shadow-xl overflow-hidden border-t-8 border-[var(--color-highlight)] relative">
            
            <div class="bg-yellow-50 p-6 border-b border-yellow-100 flex items-center justify-center gap-4">
                <i data-lucide="clock-alert" class="w-12 h-12 text-[var(--color-secondary)] flex-shrink-0"></i>
                <div class="text-left">
                     <h2 class="text-6xl uppercase font-black text-gray-800 leading-none">Off Duty</h2>
                     <p class="text-md text-black mt-1">This employee is a verified staff member but is <b>not currently clocked in</b></p>
                </div>
            </div>
            <div class="p-6 text-center">
                <div class="relative inline-block mb-4">
                    <img src="<?php echo htmlspecialchars($staff['photo_display']); ?>" class="w-24 h-24 rounded-full object-cover border-4 border-gray-100 shadow-inner grayscale opacity-80" alt="Staff Photo: <?php echo $staffFn . ' ' . $staffLn; ?>">
                </div>

                <h1 class="text-4xl font-black text-gray-500 uppercase">
                    <?php echo htmlspecialchars($staff['first_name'] . ' ' . $staff['last_name']); ?>
                </h1>
                <p class="text-md font-bold text-gray-400 uppercase mb-4">
                    <?php echo htmlspecialchars($staff['job_title']); ?>
                </p>

                <div class="bg-gray-50 rounded-lg p-3 border border-gray-200">
                    <p class="text-md font-bold text-gray-400 uppercase">Current Status</p>
                    <p class="text-2xl font-black text-[var(--color-secondary)]">NOT WORKING</p>
                </div>
                
                <div class="mt-6 pt-4 border-t border-dashed border-gray-200">
                    <p class="text-md font-black text-[var(--color-primary)] uppercase mb-3">Authorized Work Schedule</p>
                    
                    <?php if (empty($schedule_details)): ?>
                        <div class="bg-gray-100 p-3 rounded-lg border border-gray-300 mx-auto w-full max-w-xs">
                            <p class="text-xs font-black text-gray-500 uppercase">NO SCHEDULE DEFINED</p>
                            <p class="text-sm font-extrabold text-[var(--color-secondary)]">NOT AVAILABLE</p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-2 text-left w-full max-w-xs mx-auto">
                            <?php foreach($schedule_details as $item): ?>
                                <div class="bg-gray-50 p-2.5 rounded-lg border border-gray-200 flex justify-between items-center">
                                    <span class="text-xs font-black text-gray-700 uppercase w-1/4">
                                        <?php echo htmlspecialchars($item['day']); ?>
                                    </span>
                                    <span class="text-sm font-extrabold text-[var(--color-primary)] whitespace-nowrap">
                                        <?php echo htmlspecialchars($item['display']); ?>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <?php if (!empty($phone_primary)): ?>
            <a href="tel:<?php echo htmlspecialchars($phone_primary); ?>" 
               class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black mt-4 py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                <i data-lucide="phone-call" class="w-4 h-4"></i> CALL OFFICE TO CONFIRM
            </a>
            <?php endif; ?>
        </section>

    <?php elseif ($view_state === 'inactive'): ?>
        <section class="w-full bg-white rounded-2xl shadow-2xl overflow-hidden border-t-8 border-[var(--color-secondary)] relative">
            
            <div class="watermark">TERMINATED</div>

            <div class="bg-[var(--color-secondary)] p-6 text-center text-white relative z-10">
                <i data-lucide="ban" class="w-12 h-12 mx-auto mb-2 opacity-90"></i>
                <h2 class="text-2xl font-black uppercase tracking-widest">SECURITY ALERT</h2>
                <p class="text-xs font-bold opacity-80 uppercase">Invalid Credentials</p>
            </div>

            <div class="p-8 text-center relative z-10">
                <div class="relative inline-block mb-4">
                    <img src="<?php echo htmlspecialchars($staff['photo_display']); ?>" class="w-24 h-24 rounded-full object-cover border-4 border-gray-200 shadow-sm grayscale brightness-50" alt="Staff Photo: <?php echo $staffFn . ' ' . $staffLn; ?>">
                    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full">
                        <div class="bg-[var(--color-secondary)] text-white text-[10px] font-black py-1 uppercase tracking-widest -rotate-12 border-y-2 border-white shadow-lg">
                            Inactive
                        </div>
                    </div>
                </div>

                <h3 class="text-lg font-bold text-gray-400 line-through decoration-[var(--color-secondary)] decoration-2 uppercase">
                    <?php echo htmlspecialchars($staff['first_name'] . ' ' . $staff['last_name']); ?>
                </h3>
                
                <div class="mt-6 bg-red-50 border-l-4 border-[var(--color-secondary)] p-4 text-left rounded-r-lg">
                    <p class="text-xs text-[var(--color-secondary)] font-black uppercase mb-1">STATUS: NO LONGER EMPLOYED</p>
                    <p class="text-xs text-gray-700 leading-relaxed font-medium">
                        <b>This person no longer </b>works at <?php echo htmlspecialchars($ci['business_name'] ?? 'the company'); ?>. <b>Do not allow access to the property or share information</b> with them. </p>
                </div>
            </div>

            <div class="p-4 bg-gray-50 border-t border-gray-200 relative z-10">
                <a href="tel:<?php echo htmlspecialchars($phone_primary); ?>" class="flex items-center justify-center gap-2 w-full bg-[var(--color-secondary)] text-white font-bold py-3 rounded-lg uppercase text-sm shadow hover:bg-red-800 transition">
                    <i data-lucide="phone-off" class="w-4 h-4"></i> Report Activity
                </a>
            </div>
        </section>

    <?php else: ?>
        <section class="w-full bg-white rounded-2xl shadow-2xl overflow-hidden border-t-8 border-[var(--color-secondary)] text-center p-8">
            
            <div class="w-32 h-32 bg-[var(--color-secondary)] rounded-full flex items-center justify-center mx-auto mb-4 border-4 border-red-200">
                <i data-lucide="id-card-lanyard" class="w-20 h-20 text-white"></i>
            </div>
            
            <h3 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-2">ID NOT FOUND</h3>
            
            <p class="text-gray-500 text-lg mb-6">The page you just accessed does not exist or the link has expired</p>
            
            <a href="booking.php" 
                class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                <i data-lucide="calendar-plus" class="w-4 h-4"></i> 
                BOOK AN APPOINTMENT
            </a>
            
            <?php if (!empty($phone_primary)): ?>
            <a href="tel:<?php echo htmlspecialchars($phone_primary); ?>" 
               class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black mt-4 py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                <i data-lucide="phone-call" class="w-4 h-4"></i> CALL OFFICE TO HELP
            </a>
            <?php endif; ?>
            
            <p class="text-md text-gray-400 mt-4">If you believe this is an error, please contact the office.</p>
            <p class="text-lg font-black text-gray-400 mt-4 items-center justify-center"><?php echo htmlspecialchars($ci['business_name'] ?? ''); ?></p>

        </section>
    <?php endif; ?>
</main>

 <?php @include 'brand/page-footer.php'; ?>

<script>
    lucide.createIcons();
</script>
    <script src="files/toast.js"></script>
</body>
</html>