<?php
declare(strict_types=1);

/* ===== تشغيل عرض الأخطاء ===== */
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

/* ===== تحويل أخطاء PHP إلى عرض واضح ===== */
set_error_handler(function ($severity, $message, $file, $line) {
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace;direction:ltr;text-align:left'>";
    echo "<h2 style='color:#ff6b6b;margin-top:0'>PHP ERROR</h2>";
    echo "<strong>Message:</strong> " . htmlspecialchars((string)$message) . "<br><br>";
    echo "<strong>File:</strong> " . htmlspecialchars((string)$file) . "<br><br>";
    echo "<strong>Line:</strong> " . (int)$line . "<br><br>";
    echo "<strong>Severity:</strong> " . (int)$severity;
    echo "</div>";
    exit;
});

/* ===== التقاط الاستثناءات غير المعالجة ===== */
set_exception_handler(function (Throwable $e) {
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace;direction:ltr;text-align:left'>";
    echo "<h2 style='color:#ffd166;margin-top:0'>UNCAUGHT EXCEPTION</h2>";
    echo "<strong>Message:</strong> " . htmlspecialchars($e->getMessage()) . "<br><br>";
    echo "<strong>File:</strong> " . htmlspecialchars($e->getFile()) . "<br><br>";
    echo "<strong>Line:</strong> " . (int)$e->getLine() . "<br><br>";
    echo "<strong>Trace:</strong><pre style='white-space:pre-wrap;color:#9bf6ff'>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</div>";
    exit;
});

/* ===== التقاط Fatal Errors ===== */
register_shutdown_function(function () {
    $error = error_get_last();
    if ($error !== null) {
        $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR];
        if (in_array($error['type'], $fatalTypes, true)) {
            echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace;direction:ltr;text-align:left'>";
            echo "<h2 style='color:#ff4d4f;margin-top:0'>FATAL ERROR</h2>";
            echo "<strong>Message:</strong> " . htmlspecialchars((string)$error['message']) . "<br><br>";
            echo "<strong>File:</strong> " . htmlspecialchars((string)$error['file']) . "<br><br>";
            echo "<strong>Line:</strong> " . (int)$error['line'] . "<br><br>";
            echo "<strong>Type:</strong> " . (int)$error['type'];
            echo "</div>";
        }
    }
});


if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/* ===== UAE Timezone (Dubai) ===== */
date_default_timezone_set('Asia/Dubai');
$todayUAE = date('Y-m-d');

/* ===== Debug: hr_attendance.php?debug=1 ===== */
$debug = isset($_GET['debug']) && $_GET['debug'] === '1';

ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

/* ===== Error Handlers ===== */
set_exception_handler(function (Throwable $e) use ($debug): void {
    http_response_code(500);

    if (!$debug) {
        echo 'HTTP ERROR 500';
        exit;
    }

    echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
    echo "UNCAUGHT EXCEPTION\n";
    echo "Message: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n\n";
    echo $e->getTraceAsString();
    echo "</pre>";
    exit;
});

set_error_handler(function (int $severity, string $message, string $file, int $line) use ($debug): bool {
    http_response_code(500);

    if (!$debug) {
        echo 'HTTP ERROR 500';
        exit;
    }

    echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
    echo "PHP ERROR\n";
    echo "Severity: {$severity}\n";
    echo "Message: {$message}\n";
    echo "File: {$file}\n";
    echo "Line: {$line}\n";
    echo "</pre>";
    exit;
});

require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/permissions.php';
require_once __DIR__ . '/db.php';

if (function_exists('require_login')) {
    require_login();
}

$pdo = function_exists('db') ? db() : null;
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* ===== Session ===== */
$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = (int)($_SESSION['branch_id'] ?? 0);
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

if ($userId <= 0) {
    http_response_code(403);
    exit('انتهت الجلسة');
}
$pdo = function_exists('db') ? db() : null;
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* ===== Session ===== */
$userId   = (int)($_SESSION['user_id'] ?? 0);
$branchId = (int)($_SESSION['branch_id'] ?? 0);
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

if ($userId <= 0) {
    http_response_code(403);
    exit('انتهت الجلسة');
}

/* ===== تحديث النشاط ===== */
try {
    $st = $pdo->prepare("
        UPDATE employees
        SET last_activity = NOW()
        WHERE id = ?
    ");
    $st->execute([$userId]);
} catch (Throwable $e) {
    // لا توقف الصفحة
}
/* ===== Permission Helpers ===== */
if (!function_exists('has_attendance_admin_permission')) {
    function has_attendance_admin_permission(PDO $pdo, int $userId): bool
    {
        $stmt = $pdo->prepare("
            SELECT 1
            FROM employee_permissions
            WHERE employee_id = ?
              AND permission_key = 'attendance_admin'
            LIMIT 1
        ");
        $stmt->execute([$userId]);
        return (bool)$stmt->fetchColumn();
    }
}

$isSystemAdmin = in_array($role, ['OWNER', 'ADMIN'], true);
$isAttendanceAdmin = $isSystemAdmin || has_attendance_admin_permission($pdo, $userId);

/* ===== Access Model =====
   - كل الموظفين يدخلون الصفحة
   - الأدمن أو من لديه attendance_admin يشوف كل الموظفين
   - الموظف العادي يشوف نفسه فقط
*/
$canAccessAttendancePage = true;
$canViewAllAttendance    = $isAttendanceAdmin;
$canManageAttendance     = $isAttendanceAdmin;

/* ===== Selected Date ===== */
$selectedDate = trim((string)($_GET['date'] ?? $todayUAE));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDate)) {
    $selectedDate = $todayUAE;
}


/* ===== Helpers ===== */
if (!function_exists('h')) {
    function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

/* ===== صلاحية الإدارة داخل الصفحة فقط ===== */
function attendance_is_admin(): bool
{
    if (function_exists('has_any_permission') && has_any_permission(['attendance_admin'])) {
        return true;
    }

    $role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
    return in_array($role, ['OWNER', 'ADMIN'], true);
}

function table_cols(PDO $pdo, string $table): array
{
    try {
        $st = $pdo->query("SHOW COLUMNS FROM `$table`");
        return $st->fetchAll(PDO::FETCH_COLUMN, 0);
    } catch (Throwable $e) {
        return [];
    }
}

function now_dubai(): array
{
    $dt = new DateTime('now', new DateTimeZone('Asia/Dubai'));
    return [
        'datetime' => $dt->format('Y-m-d H:i:s'),
        'time'     => $dt->format('H:i:s'),
    ];
}

function employee_exists_for_branch(PDO $pdo, int $empId, bool $empHasBranch, bool $empHasStatus, int $branchId): bool
{
    $sql = "SELECT e.id FROM employees e WHERE e.id=?";
    $args = [$empId];

    if ($empHasBranch) {
        $sql .= " AND e.branch_id=?";
        $args[] = $branchId;
    }

    if ($empHasStatus) {
        $sql .= " AND e.status='ACTIVE'";
    }

    $sql .= " LIMIT 1";
    $st = $pdo->prepare($sql);
    $st->execute($args);

    return (bool)$st->fetchColumn();
}

function build_update_sql(string $table, array $sets, string $where): ?string
{
    if (!$sets) {
        return null;
    }
    return "UPDATE {$table} SET " . implode(',', $sets) . " WHERE {$where}";

}
/* ===== Attendance + Leave Helpers ===== */
function attendance_branch_key(int $branchId): string
{
    if ($branchId === 2) {
        return 'dubai';
    }

    if ($branchId === 1) {
        return 'abudhabi';
    }

    $name = trim((string)(
        $_SESSION['branch_name'] ??
        $_SESSION['branch_title'] ??
        $_SESSION['branch'] ??
        ''
    ));

    $nameNorm = mb_strtolower($name, 'UTF-8');

    if (
        strpos($nameNorm, 'dubai') !== false ||
        strpos($nameNorm, 'دبي') !== false
    ) {
        return 'dubai';
    }

    return 'abudhabi';
}
function attendance_branch_label(string $branchKey): string
{
    if ($branchKey === 'dubai') {
        return 'دبي';
    }

    return 'أبوظبي';
}

function attendance_schedule_for_date(string $branchKey, string $date): array
{
    $weekday = (int)(new DateTime($date, new DateTimeZone('Asia/Dubai')))->format('w');
    // 0=Sunday, 1=Monday ... 6=Saturday

    if ($branchKey === 'abudhabi') {

        // الاثنين - الخميس
        if (in_array($weekday, [1, 2, 3, 4], true)) {
            return [
                'is_off'      => false,
                'start'       => '09:00:00',
                'end'         => '18:00:00',
                'start_label' => '9:00 صباحاً',
                'end_label'   => '6:00 مساءً',
                'text'        => 'الاثنين - الخميس: 9:00 صباحاً - 6:00 مساءً',
            ];
        }

        // الجمعة
        if ($weekday === 5) {
            return [
                'is_off'      => false,
                'start'       => '09:00:00',
                'end'         => '17:00:00',
                'start_label' => '9:00 صباحاً',
                'end_label'   => '5:00 مساءً',
                'text'        => 'الجمعة: 9:00 صباحاً - 5:00 مساءً',
            ];
        }

        // السبت والأحد عطلة
        return [
            'is_off'      => true,
            'start'       => null,
            'end'         => null,
            'start_label' => '-',
            'end_label'   => '-',
            'text'        => 'إجازة',
        ];
    }

    if (in_array($weekday, [1, 2, 3, 4, 5], true)) {
        return [
            'is_off'      => false,
            'start'       => '09:00:00',
            'end'         => '17:00:00',
            'start_label' => '9:00 صباحاً',
            'end_label'   => '5:00 مساءً',
            'text'        => 'الاثنين - الجمعة: 9:00 صباحاً - 5:00 مساءً',
        ];
    }

    return [
        'is_off'      => true,
        'start'       => null,
        'end'         => null,
        'start_label' => '-',
        'end_label'   => '-',
        'text'        => 'إجازة',
    ];
}

function attendance_dt(?string $value): ?DateTime
{
    $v = trim((string)$value);
    if ($v === '' || $v === '0000-00-00 00:00:00') {
        return null;
    }

    try {
        return new DateTime($v, new DateTimeZone('Asia/Dubai'));
    } catch (Throwable $e) {
        return null;
    }
}

function attendance_time_only(?string $value): ?string
{
    $dt = attendance_dt($value);
    return $dt ? $dt->format('H:i:s') : null;
}

function attendance_display_time(?string $value): string
{
    $dt = attendance_dt($value);
    return $dt ? $dt->format('Y-m-d h:i A') : '';
}

function attendance_compare_times(string $time1, string $time2): int
{
    return strcmp($time1, $time2);
}

function attendance_leave_status_label(?string $leaveType): string
{
    $t = strtoupper(trim((string)$leaveType));

    return match ($t) {
        'ANNUAL', 'سنوية'          => 'إجازة سنوية',
        'SICK', 'مرضية'            => 'إجازة مرضية',
        'EMERGENCY', 'طارئة'       => 'إجازة طارئة',
        'UNPAID', 'WITHOUT_PAY', 'بدون راتب' => 'إجازة بدون راتب',
        'MATERNITY', 'أمومة'       => 'إجازة أمومة',
        'PATERNITY', 'أبوة'        => 'إجازة أبوة',
        default                    => 'في إجازة',
    };
}

function attendance_has_approved_leave(?string $leaveType, ?string $leaveStatus): bool
{
    $type = trim((string)$leaveType);
    $status = strtoupper(trim((string)$leaveStatus));

    if ($type === '') {
        return false;
    }

    return in_array($status, ['APPROVED', 'APPROVE', 'معتمد', 'موافق', 'موافقة'], true);
}

function attendance_status_label(
    ?string $status,
    ?string $checkIn = null,
    ?string $checkOut = null,
    ?array $schedule = null,
    ?string $logDate = null,
    ?string $leaveType = null,
    ?string $leaveStatus = null
): string {
    if (attendance_has_approved_leave($leaveType, $leaveStatus)) {
        return attendance_leave_status_label($leaveType);
    }

    $hasIn = !empty($checkIn);
    $hasOut = !empty($checkOut);

    $today = date('Y-m-d');
    $nowTime = date('H:i:s');
    $targetDate = trim((string)$logDate);

    if ($schedule && !empty($schedule['is_off'])) {
        return ($hasIn || $hasOut) ? 'دوام في يوم إجازة' : 'خارج نطاق العمل';
    }

    if (!$hasIn && !$hasOut) {
        if ($schedule && !empty($schedule['start']) && !empty($schedule['end'])) {
            if ($targetDate === $today) {
                if ($nowTime < (string)$schedule['start']) {
                    return 'خارج نطاق العمل';
                }
                return 'غياب';
            }

            if ($targetDate < $today) {
                return 'غياب';
            }

            if ($targetDate > $today) {
                return 'خارج نطاق العمل';
            }
        }

        return 'غياب';
    }

    $inTime  = attendance_time_only($checkIn);
    $outTime = attendance_time_only($checkOut);

    if ($hasIn && !$hasOut) {
        if ($schedule && !empty($schedule['start']) && $inTime !== null) {
            if (attendance_compare_times($inTime, (string)$schedule['start']) > 0) {
                return 'متأخر';
            }
        }
        return 'حاضر';
    }

    if ($hasIn && $hasOut) {
        if ($schedule && !empty($schedule['end']) && $outTime !== null) {
            if (attendance_compare_times($outTime, (string)$schedule['end']) < 0) {
                return 'خروج مبكر';
            }
        }
        return 'منصرف';
    }

    $s = strtoupper(trim((string)$status));

    return match ($s) {
        'PRESENT', 'P', 'IN', 'CHECKED_IN', 'حاضر' => 'حاضر',
        'LEFT', 'OUT', 'CHECKED_OUT', 'منصرف' => 'منصرف',
        'ABSENT', 'A', 'غياب' => 'غياب',
        'LATE', 'متأخر' => 'متأخر',
        'PENDING', 'قيد المراجعة' => 'قيد المراجعة',
        default => (string)$status,
    };
}

function attendance_status_class(
    ?string $status,
    ?string $checkIn = null,
    ?string $checkOut = null,
    ?array $schedule = null,
    ?string $logDate = null,
    ?string $leaveType = null,
    ?string $leaveStatus = null
): string {
    $label = attendance_status_label(
        $status,
        $checkIn,
        $checkOut,
        $schedule,
        $logDate,
        $leaveType,
        $leaveStatus
    );

    return match ($label) {
        'حاضر'              => 'st-present',
        'منصرف'             => 'st-left',
        'غياب'              => 'st-absent',
        'متأخر'             => 'st-late',
        'خروج مبكر'         => 'st-early',
        'خارج نطاق العمل'   => 'st-off',
        'دوام في يوم إجازة' => 'st-offwork',
        'إجازة سنوية',
        'إجازة مرضية',
        'إجازة طارئة',
        'إجازة بدون راتب',
        'إجازة أمومة',
        'إجازة أبوة',
        'في إجازة'          => 'st-leave',
        default             => 'st-pending',
    };
}

function attendance_build_note(
    string $existingNote,
    array $schedule,
    ?string $checkInDT,
    ?string $checkOutDT,
    ?string $logDate = null,
    ?string $leaveType = null,
    ?string $leaveStatus = null
): string {
    $notes = [];
    $base = trim($existingNote);
    if ($base !== '') {
        $notes[] = $base;
    }

    if (attendance_has_approved_leave($leaveType, $leaveStatus)) {
        $notes[] = 'إجازة معتمدة';
        return implode(' | ', array_unique($notes));
    }

    $today = date('Y-m-d');
    $nowTime = date('H:i:s');
    $targetDate = trim((string)$logDate);

    if (!empty($schedule['is_off'])) {
        if (!empty($checkInDT) || !empty($checkOutDT)) {
            $notes[] = 'تم التسجيل خارج نطاق العمل';
        } else {
            $notes[] = 'اليوم خارج نطاق العمل';
        }
        return implode(' | ', array_unique($notes));
    }

    if (empty($checkInDT) && empty($checkOutDT) && $targetDate === $today) {
        if (!empty($schedule['start']) && !empty($schedule['end'])) {
            if ($nowTime < (string)$schedule['start'] || $nowTime > (string)$schedule['end']) {
                $notes[] = 'حالياً خارج نطاق العمل';
                return implode(' | ', array_unique($notes));
            }
        }
    }

    $inTime  = attendance_time_only($checkInDT);
    $outTime = attendance_time_only($checkOutDT);

    if ($inTime !== null && !empty($schedule['start']) && attendance_compare_times($inTime, (string)$schedule['start']) > 0) {
        $notes[] = 'متأخر عن موعد الدوام';
    }

    if ($outTime !== null && !empty($schedule['end']) && attendance_compare_times($outTime, (string)$schedule['end']) < 0) {
        $notes[] = 'انصراف مبكر';
    }

    return implode(' | ', array_unique($notes));
}

function attendance_employee_has_approved_leave(PDO $pdo, int $employeeId, string $day): bool
{
    try {
        $cols = table_cols($pdo, 'leave_requests');
        if (!$cols) {
            return false;
        }

        $required = ['employee_id', 'date_from', 'date_to', 'status'];
        foreach ($required as $col) {
            if (!in_array($col, $cols, true)) {
                return false;
            }
        }

        $sql = "
            SELECT 1
            FROM leave_requests lr
            WHERE lr.employee_id = ?
              AND ? BETWEEN lr.date_from AND lr.date_to
              AND UPPER(TRIM(lr.status)) IN ('APPROVED','APPROVE','معتمد','موافق','موافقة')
            LIMIT 1
        ";

        $st = $pdo->prepare($sql);
        $st->execute([$employeeId, $day]);
        return (bool)$st->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}

/* ===== Session / Identity ===== */
$branchId = function_exists('current_branch_id') ? (int)current_branch_id() : (int)($_SESSION['branch_id'] ?? 1);
$userId   = function_exists('current_user_id') ? (int)current_user_id() : (int)($_SESSION['user_id'] ?? 0);
$role     = strtoupper((string)($_SESSION['role'] ?? (function_exists('current_role') ? current_role() : 'STAFF')));

$canManageAttendance = attendance_is_admin();

$msg = '';
$err = '';

$day = (string)($_GET['day'] ?? $todayUAE);
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $day)) {
    $day = $todayUAE;
}

$branchKey     = attendance_branch_key($branchId);
$branchLabel   = attendance_branch_label($branchKey);
$selectedShift = attendance_schedule_for_date($branchKey, $day);

/* ===== Detect Columns ===== */
$empCols   = table_cols($pdo, 'employees');
$attCols   = table_cols($pdo, 'attendance_logs');
$leaveCols = table_cols($pdo, 'leave_requests');

$empHasBranch = in_array('branch_id', $empCols, true);
$empHasStatus = in_array('status', $empCols, true);
$empHasQr1    = in_array('qr_token', $empCols, true);
$empHasQr2    = in_array('qr_token2', $empCols, true);
$empHasUserId = in_array('user_id', $empCols, true);

$nameExpr = in_array('full_name', $empCols, true)
    ? "e.full_name"
    : (in_array('name', $empCols, true) ? "e.name" : "CONCAT('EMP#', e.id)");

$attHasId        = in_array('id', $attCols, true);
$attHasCheckIn   = in_array('check_in', $attCols, true);
$attHasCheckOut  = in_array('check_out', $attCols, true);
$attHasStatus    = in_array('status', $attCols, true);
$attHasLogTime   = in_array('log_time', $attCols, true);
$attHasNote      = in_array('note', $attCols, true);
$attHasNotes     = in_array('notes', $attCols, true);
$attHasCreatedBy = in_array('created_by', $attCols, true);

$leaveTableReady =
    !empty($leaveCols) &&
    in_array('employee_id', $leaveCols, true) &&
    in_array('date_from', $leaveCols, true) &&
    in_array('date_to', $leaveCols, true) &&
    in_array('status', $leaveCols, true);

$leaveTypeExpr = in_array('leave_type', $leaveCols, true) ? "lr.leave_type" : "NULL";

if (!$attHasId || !in_array('employee_id', $attCols, true) || !in_array('log_date', $attCols, true)) {
    throw new RuntimeException('attendance_logs يجب أن يحتوي على id و employee_id و log_date');
}

/* ===== Link employee to current user for STAFF ===== */
$sessionEmpId = (int)($_SESSION['employee_id'] ?? 0);

try {
    if (!$canManageAttendance && $sessionEmpId <= 0 && $empHasUserId && $userId > 0) {
        $sql = "SELECT e.id
                FROM employees e
                WHERE e.user_id=?";
        $args = [$userId];

        if ($empHasBranch) {
            $sql .= " AND e.branch_id=?";
            $args[] = $branchId;
        }

        if ($empHasStatus) {
            $sql .= " AND e.status='ACTIVE'";
        }

        $sql .= " ORDER BY e.id DESC LIMIT 1";

        $st = $pdo->prepare($sql);
        $st->execute($args);

        $sessionEmpId = (int)($st->fetchColumn() ?: 0);

        if ($sessionEmpId > 0) {
            $_SESSION['employee_id'] = $sessionEmpId;
        }
    }
} catch (Throwable $e) {
    if ($debug) {
        $err = 'EMP LINK ERROR: ' . $e->getMessage();
    }
}

/* ===== Current employee data for STAFF ===== */
$me = null;

if (!$canManageAttendance && $sessionEmpId > 0) {
    $sql = "SELECT e.id, {$nameExpr} AS full_name
            FROM employees e
            WHERE e.id=?";
    $args = [$sessionEmpId];

    if ($empHasBranch) {
        $sql .= " AND e.branch_id=?";
        $args[] = $branchId;
    }

    if ($empHasStatus) {
        $sql .= " AND e.status='ACTIVE'";
    }

    $sql .= " LIMIT 1";

    $st = $pdo->prepare($sql);
    $st->execute($args);
    $me = $st->fetch(PDO::FETCH_ASSOC) ?: null;

    if (!$me) {
        $sessionEmpId = 0;
        $_SESSION['employee_id'] = 0;
    }
}

/* ===== POST Actions ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action  = (string)($_POST['action'] ?? '');
    $now     = now_dubai();
    $nowDT   = $now['datetime'];
    $nowTime = $now['time'];

    $todayShift = attendance_schedule_for_date($branchKey, $day);
    $isOffDay   = !empty($todayShift['is_off']);

    if ($action === 'scan_qr') {
        $token = preg_replace('/\s+/u', '', trim((string)($_POST['qr_token'] ?? '')));
        $note  = trim((string)($_POST['note'] ?? ''));

        if ($token === '') {
            $err = 'QR غير صالح';
        } else {
            $where = [];
            $args  = [];

            if ($empHasQr1) {
                $where[] = "e.qr_token = ?";
                $args[]  = $token;
            }

            if ($empHasQr2) {
                $where[] = "e.qr_token2 = ?";
                $args[]  = $token;
            }

            if (!$where) {
                $err = 'لا توجد حقول QR في جدول employees';
            } else {
                $sqlEmp = "SELECT e.id, {$nameExpr} AS full_name
                           FROM employees e
                           WHERE (" . implode(' OR ', $where) . ")";

                if ($empHasBranch) {
                    $sqlEmp .= " AND e.branch_id=?";
                    $args[] = $branchId;
                }

                if ($empHasStatus) {
                    $sqlEmp .= " AND e.status='ACTIVE'";
                }

                $sqlEmp .= " LIMIT 1";

                $st = $pdo->prepare($sqlEmp);
                $st->execute($args);
                $emp = $st->fetch(PDO::FETCH_ASSOC);

                if (!$emp) {
                    $err = 'الموظف غير موجود في هذا الفرع أو غير نشط';
                } else {
                    $empId = (int)$emp['id'];

                    if (!$canManageAttendance && $sessionEmpId > 0 && $empId !== $sessionEmpId) {
                        $err = 'هذا الكود لا يطابق حسابك';
                    } else {
                        if (!$canManageAttendance && $sessionEmpId <= 0) {
                            $_SESSION['employee_id'] = $empId;
                            $sessionEmpId = $empId;
                            $me = [
                                'id'        => $empId,
                                'full_name' => (string)($emp['full_name'] ?? ''),
                            ];
                        }

                        if (attendance_employee_has_approved_leave($pdo, $empId, $day)) {
                            $err = 'هذا الموظف في إجازة معتمدة اليوم ولا يمكن تسجيل الحضور أو الانصراف';
                        } elseif ($isOffDay) {
                            $err = 'اليوم إجازة رسمية لهذا الفرع ولا يمكن تسجيل الحضور أو الانصراف';
                        } else {
                            $st = $pdo->prepare("SELECT id, check_in, check_out FROM attendance_logs WHERE employee_id=? AND log_date=? LIMIT 1");
                            $st->execute([$empId, $day]);
                            $log = $st->fetch(PDO::FETCH_ASSOC);

                            if (!$log) {
                                $fields = ['employee_id', 'log_date'];
                                $vals   = [$empId, $day];

                                if ($attHasStatus) {
                                    $fields[] = 'status';
                                    $vals[]   = 'حاضر';
                                }

                                if ($attHasCheckIn) {
                                    $fields[] = 'check_in';
                                    $vals[]   = $nowDT;
                                }

                                if ($attHasLogTime) {
                                    $fields[] = 'log_time';
                                    $vals[]   = $nowTime;
                                }

                                if ($attHasCreatedBy) {
                                    $fields[] = 'created_by';
                                    $vals[]   = $userId;
                                }

                                if ($attHasNote) {
                                    $fields[] = 'note';
                                    $vals[]   = ($note !== '' ? $note : null);
                                }

                                if ($attHasNotes) {
                                    $fields[] = 'notes';
                                    $vals[]   = ($note !== '' ? $note : null);
                                }

                                $ph = implode(',', array_fill(0, count($fields), '?'));
                                $sqlIns = "INSERT INTO attendance_logs (" . implode(',', $fields) . ") VALUES ({$ph})";
                                $st = $pdo->prepare($sqlIns);
                                $st->execute($vals);

                                $msg = 'تم تسجيل الدخول: ' . (string)($emp['full_name'] ?? '');
                            } else {
                                $logId  = (int)$log['id'];
                                $hasIn  = !empty($log['check_in']);
                                $hasOut = !empty($log['check_out']);

                                if (!$hasIn) {
                                    $set  = [];
                                    $vals = [];

                                    if ($attHasCheckIn) {
                                        $set[]  = "check_in=?";
                                        $vals[] = $nowDT;
                                    }

                                    if ($attHasStatus) {
                                        $set[] = "status='حاضر'";
                                    }

                                    if ($attHasLogTime) {
                                        $set[]  = "log_time=?";
                                        $vals[] = $nowTime;
                                    }

                                    if ($attHasNote) {
                                        $set[]  = "note=?";
                                        $vals[] = ($note !== '' ? $note : null);
                                    }

                                    if ($attHasNotes) {
                                        $set[]  = "notes=?";
                                        $vals[] = ($note !== '' ? $note : null);
                                    }

                                    $vals[] = $logId;
                                    $sqlUp = build_update_sql('attendance_logs', $set, 'id=?');

                                    if ($sqlUp !== null) {
                                        $st = $pdo->prepare($sqlUp);
                                        $st->execute($vals);
                                    }

                                    $msg = 'تم تسجيل الدخول: ' . (string)($emp['full_name'] ?? '');
                                } elseif (!$hasOut) {
                                    $set  = [];
                                    $vals = [];

                                    if ($attHasCheckOut) {
                                        $set[]  = "check_out=?";
                                        $vals[] = $nowDT;
                                    }

                                    if ($attHasStatus) {
                                        $set[] = "status='منصرف'";
                                    }

                                    if ($attHasLogTime) {
                                        $set[]  = "log_time=?";
                                        $vals[] = $nowTime;
                                    }

                                    if ($attHasNote) {
                                        $set[]  = "note=?";
                                        $vals[] = ($note !== '' ? $note : null);
                                    }

                                    if ($attHasNotes) {
                                        $set[]  = "notes=?";
                                        $vals[] = ($note !== '' ? $note : null);
                                    }

                                    $vals[] = $logId;
                                    $sqlUp = build_update_sql('attendance_logs', $set, 'id=?');

                                    if ($sqlUp !== null) {
                                        $st = $pdo->prepare($sqlUp);
                                        $st->execute($vals);
                                    }

                                    $msg = 'تم تسجيل الخروج: ' . (string)($emp['full_name'] ?? '');
                                } else {
                                    $msg = 'تم تسجيل هذا الموظف مسبقاً اليوم دخولاً وخروجاً.';
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if ($action === 'checkin' || $action === 'checkout') {
        $postedEmpId = (int)($_POST['employee_id'] ?? 0);
        $note        = trim((string)($_POST['note'] ?? ''));

        $empId = $canManageAttendance ? $postedEmpId : (int)($_SESSION['employee_id'] ?? 0);

        if ($empId > 0 && attendance_employee_has_approved_leave($pdo, $empId, $day)) {
            $err = 'هذا الموظف في إجازة معتمدة اليوم ولا يمكن تسجيل الحضور أو الانصراف';
        } elseif ($isOffDay) {
            $err = 'اليوم إجازة رسمية لهذا الفرع ولا يمكن تسجيل الحضور أو الانصراف';
        } elseif ($empId <= 0) {
            $err = $canManageAttendance ? 'اختر الموظف' : 'تعذر تحديد الموظف';
        } elseif (!employee_exists_for_branch($pdo, $empId, $empHasBranch, $empHasStatus, $branchId)) {
            $err = 'الموظف غير موجود في هذا الفرع أو غير نشط';
        }

        if ($err === '') {
            $fields = ['employee_id', 'log_date'];
            $vals   = [$empId, $day];

            if ($attHasStatus) {
                $fields[] = 'status';
                $vals[]   = 'قيد المراجعة';
            }

            if ($attHasLogTime) {
                $fields[] = 'log_time';
                $vals[]   = $nowTime;
            }

            if ($attHasCreatedBy) {
                $fields[] = 'created_by';
                $vals[]   = $userId;
            }

            $ph = implode(',', array_fill(0, count($fields), '?'));

            if ($attHasCreatedBy) {
                $sqlIns = "INSERT INTO attendance_logs (" . implode(',', $fields) . ") VALUES ({$ph})
                           ON DUPLICATE KEY UPDATE created_by=VALUES(created_by)";
            } else {
                $sqlIns = "INSERT INTO attendance_logs (" . implode(',', $fields) . ") VALUES ({$ph})
                           ON DUPLICATE KEY UPDATE employee_id=employee_id";
            }

            $st = $pdo->prepare($sqlIns);
            $st->execute($vals);

            if ($action === 'checkin') {
                $set  = [];
                $vals = [];

                if ($attHasCheckIn) {
                    $set[]  = "check_in=COALESCE(check_in, ?)";
                    $vals[] = $nowDT;
                }

                if ($attHasStatus) {
                    $set[] = "status='حاضر'";
                }

                if ($attHasLogTime) {
                    $set[]  = "log_time=?";
                    $vals[] = $nowTime;
                }

                if ($attHasNote) {
                    $set[]  = "note=?";
                    $vals[] = ($note !== '' ? $note : null);
                }

                if ($attHasNotes) {
                    $set[]  = "notes=?";
                    $vals[] = ($note !== '' ? $note : null);
                }

                $vals[] = $empId;
                $vals[] = $day;

                $sqlUp = build_update_sql('attendance_logs', $set, 'employee_id=? AND log_date=?');
                if ($sqlUp !== null) {
                    $st = $pdo->prepare($sqlUp);
                    $st->execute($vals);
                }

                $msg = 'تم تسجيل الدخول';
            }

            if ($action === 'checkout') {
                $set  = [];
                $vals = [];

                if ($attHasCheckOut) {
                    $set[]  = "check_out=COALESCE(check_out, ?)";
                    $vals[] = $nowDT;
                }

                if ($attHasStatus) {
                    $set[] = "status='منصرف'";
                }

                if ($attHasLogTime) {
                    $set[]  = "log_time=?";
                    $vals[] = $nowTime;
                }

                if ($attHasNote) {
                    $set[]  = "note=?";
                    $vals[] = ($note !== '' ? $note : null);
                }

                if ($attHasNotes) {
                    $set[]  = "notes=?";
                    $vals[] = ($note !== '' ? $note : null);
                }

                $vals[] = $empId;
                $vals[] = $day;

                $sqlUp = build_update_sql('attendance_logs', $set, 'employee_id=? AND log_date=?');
                if ($sqlUp !== null) {
                    $st = $pdo->prepare($sqlUp);
                    $st->execute($vals);
                }

                $msg = 'تم تسجيل الخروج';
            }
        }
    }
}

/* ===== Employees list ===== */
$emps = [];

if ($canManageAttendance) {
    $sqlEmps = "SELECT e.id, {$nameExpr} AS full_name"
        . ($empHasQr1 ? ", e.qr_token" : "")
        . ($empHasQr2 ? ", e.qr_token2" : "")
        . " FROM employees e";

    $args = [];
    $where = [];

    if ($empHasBranch) {
        $where[] = "e.branch_id=?";
        $args[]  = $branchId;
    }

    if ($empHasStatus) {
        $where[] = "e.status='ACTIVE'";
    }

    if ($where) {
        $sqlEmps .= " WHERE " . implode(' AND ', $where);
    }

    $sqlEmps .= " ORDER BY {$nameExpr} ASC";

    $st = $pdo->prepare($sqlEmps);
    $st->execute($args);
    $emps = $st->fetchAll(PDO::FETCH_ASSOC);
} else {
    if ($me) {
        $emps = [$me];
    }
}

$sessionEmpId = (int)($_SESSION['employee_id'] ?? 0);

if (!$canManageAttendance) {
    if ($sessionEmpId > 0) {
        $emps = array_values(array_filter($emps, static function ($e) use ($sessionEmpId) {
            return (int)$e['id'] === $sessionEmpId;
        }));
    } else {
        $emps = [];
    }
}

/* ===== Daily logs ===== */
$logs = [];

if ($canManageAttendance) {
    if ($leaveTableReady) {
        $sqlLogs = "
            SELECT
                e.id AS employee_id,
                {$nameExpr} AS full_name,
                COALESCE(a.status, 'غياب') AS status,
                a.check_in,
                a.check_out,
                " . ($attHasNote ? "a.note" : ($attHasNotes ? "a.notes AS note" : "NULL AS note")) . ",
                {$leaveTypeExpr} AS leave_type,
                lr.status AS leave_status
            FROM employees e
            LEFT JOIN attendance_logs a
                ON a.employee_id = e.id AND a.log_date = ?
            LEFT JOIN leave_requests lr
                ON lr.employee_id = e.id
               AND ? BETWEEN lr.date_from AND lr.date_to
               AND UPPER(TRIM(lr.status)) IN ('APPROVED','APPROVE','معتمد','موافق','موافقة')
        ";

        $args = [$day, $day];
    } else {
        $sqlLogs = "
            SELECT
                e.id AS employee_id,
                {$nameExpr} AS full_name,
                COALESCE(a.status, 'غياب') AS status,
                a.check_in,
                a.check_out,
                " . ($attHasNote ? "a.note" : ($attHasNotes ? "a.notes AS note" : "NULL AS note")) . ",
                NULL AS leave_type,
                NULL AS leave_status
            FROM employees e
            LEFT JOIN attendance_logs a
                ON a.employee_id = e.id AND a.log_date = ?
        ";

        $args = [$day];
    }

    $where = [];

    if ($empHasBranch) {
        $where[] = "e.branch_id=?";
        $args[]  = $branchId;
    }

    if ($empHasStatus) {
        $where[] = "e.status='ACTIVE'";
    }

    if ($where) {
        $sqlLogs .= " WHERE " . implode(' AND ', $where);
    }

    $sqlLogs .= " ORDER BY {$nameExpr} ASC";

    $st = $pdo->prepare($sqlLogs);
    $st->execute($args);
    $logs = $st->fetchAll(PDO::FETCH_ASSOC);
} else {
    if ($sessionEmpId > 0) {
        if ($leaveTableReady) {
            $sqlLogs = "
                SELECT
                    e.id AS employee_id,
                    {$nameExpr} AS full_name,
                    COALESCE(a.status, 'غياب') AS status,
                    a.check_in,
                    a.check_out,
                    " . ($attHasNote ? "a.note" : ($attHasNotes ? "a.notes AS note" : "NULL AS note")) . ",
                    {$leaveTypeExpr} AS leave_type,
                    lr.status AS leave_status
                FROM employees e
                LEFT JOIN attendance_logs a
                    ON a.employee_id = e.id AND a.log_date = ?
                LEFT JOIN leave_requests lr
                    ON lr.employee_id = e.id
                   AND ? BETWEEN lr.date_from AND lr.date_to
                   AND UPPER(TRIM(lr.status)) IN ('APPROVED','APPROVE','معتمد','موافق','موافقة')
                WHERE e.id = ?
            ";

            $args = [$day, $day, $sessionEmpId];
        } else {
            $sqlLogs = "
                SELECT
                    e.id AS employee_id,
                    {$nameExpr} AS full_name,
                    COALESCE(a.status, 'غياب') AS status,
                    a.check_in,
                    a.check_out,
                    " . ($attHasNote ? "a.note" : ($attHasNotes ? "a.notes AS note" : "NULL AS note")) . ",
                    NULL AS leave_type,
                    NULL AS leave_status
                FROM employees e
                LEFT JOIN attendance_logs a
                    ON a.employee_id = e.id AND a.log_date = ?
                WHERE e.id = ?
            ";

            $args = [$day, $sessionEmpId];
        }

        if ($empHasBranch) {
            $sqlLogs .= " AND e.branch_id=?";
            $args[] = $branchId;
        }

        if ($empHasStatus) {
            $sqlLogs .= " AND e.status='ACTIVE'";
        }

        $sqlLogs .= " LIMIT 1";

        $st = $pdo->prepare($sqlLogs);
        $st->execute($args);
        $one = $st->fetch(PDO::FETCH_ASSOC);

        if ($one) {
            $logs = [$one];
        }
    }
}

if (!function_exists('render_layout_start') || !function_exists('render_layout_end')) {
    throw new RuntimeException('Functions render_layout_start / render_layout_end not found in inc/layout.php');
}

render_layout_start('شؤون الموظفين - الحضور');
?>

<style>
.grid{
    display:grid;
    gap:16px;
}
.msg{
    padding:12px 14px;
    border-radius:14px;
    border:1px solid rgba(255,255,255,.08);
}
.msg.ok{
    background:rgba(16,185,129,.10);
    color:#d1fae5;
    border-color:rgba(16,185,129,.35);
}
.msg.err{
    background:rgba(239,68,68,.10);
    color:#fee2e2;
    border-color:rgba(239,68,68,.35);
}
.card{
    border:1px solid rgba(255,255,255,.08);
    border-radius:20px;
    padding:16px;
    background:linear-gradient(180deg, rgba(3,28,35,.96), rgba(5,44,54,.96));
}
.cardHead{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:14px;
    flex-wrap:wrap;
}
.row{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
}
.input, .select{
    width:100%;
    min-height:44px;
    border-radius:12px;
    border:1px solid rgba(255,255,255,.10);
    background:rgba(255,255,255,.04);
    color:#fff;
    padding:10px 12px;
    outline:none;
}
.select option{
    color:#111;
}
.input::placeholder{
    color:rgba(255,255,255,.45);
}
.btn{
    min-height:44px;
    border:none;
    border-radius:12px;
    padding:0 16px;
    cursor:pointer;
    color:#fff;
    background:#0c7c8c;
}
.btn:hover{
    filter:brightness(1.08);
}
.btn.ghost{
    background:rgba(255,255,255,.08);
}
.print-btn{
    background:#16a34a;
}
.print-btn:hover{
    filter:brightness(1.05);
}
.muted{
    color:rgba(255,255,255,.65);
    font-size:13px;
}
table{
    width:100%;
    border-collapse:collapse;
    min-width:900px;
}
th,td{
    padding:14px 12px;
    border-bottom:1px solid rgba(255,255,255,.08);
    text-align:right;
    vertical-align:middle;
}
th{
    color:#fff;
}
td{
    color:#e8f3f5;
}
.status-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:100px;
    padding:7px 12px;
    border-radius:999px;
    font-size:13px;
    border:1px solid transparent;
}
.st-present{
    background:rgba(16,185,129,.14);
    color:#d1fae5;
    border-color:rgba(16,185,129,.35);
}
.st-left{
    background:rgba(59,130,246,.14);
    color:#dbeafe;
    border-color:rgba(59,130,246,.35);
}
.st-absent{
    background:rgba(239,68,68,.14);
    color:#fee2e2;
    border-color:rgba(239,68,68,.35);
}
.st-late{
    background:rgba(245,158,11,.14);
    color:#fef3c7;
    border-color:rgba(245,158,11,.35);
}
.st-early{
    background:rgba(251,146,60,.14);
    color:#ffedd5;
    border-color:rgba(251,146,60,.35);
}
.st-off{
    background:rgba(148,163,184,.14);
    color:#e2e8f0;
    border-color:rgba(148,163,184,.35);
}
.st-offwork{
    background:rgba(168,85,247,.14);
    color:#f3e8ff;
    border-color:rgba(168,85,247,.35);
}
.st-leave{
    background:rgba(34,197,94,.14);
    color:#dcfce7;
    border-color:rgba(34,197,94,.35);
}
.st-pending{
    background:rgba(148,163,184,.14);
    color:#e2e8f0;
    border-color:rgba(148,163,184,.35);
}
.actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    align-items:flex-end;
}
.field{
    min-width:220px;
    flex:1;
}
.shiftBox{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:12px;
    margin-bottom:12px;
}
.shiftItem{
    border:1px solid rgba(255,255,255,.08);
    border-radius:16px;
    padding:12px;
    background:rgba(255,255,255,.03);
}
.shiftLabel{
    font-size:12px;
    color:rgba(255,255,255,.60);
    margin-bottom:6px;
}
.shiftValue{
    font-size:16px;
    color:#fff;
}
.print-header{
    display:none;
}
.print-company{
    text-align:center;
    font-size:16px;
    font-weight:700;
    margin-bottom:6px;
    color:#000;
}
.print-title{
    text-align:center;
    font-size:24px;
    font-weight:700;
    margin-bottom:14px;
    color:#000;
}
.print-meta{
    display:flex;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:16px;
    color:#000;
    font-size:14px;
}
@media (max-width: 900px){
    .cardHead{
        align-items:stretch;
    }
}
@media print{
    body{
        background:#fff !important;
        color:#000 !important;
    }

    .no-print,
    .msg,
    script{
        display:none !important;
    }

    .card{
        background:#fff !important;
        border:none !important;
        box-shadow:none !important;
        padding:0 !important;
    }

    #attendancePrintArea{
        display:block !important;
    }

    .print-header{
        display:block !important;
    }

    table{
        width:100% !important;
        min-width:0 !important;
        border-collapse:collapse !important;
    }

    th, td{
        border:1px solid #000 !important;
        padding:8px !important;
        color:#000 !important;
        background:#fff !important;
        text-align:right !important;
        font-size:12px !important;
    }

    th{
        font-weight:700 !important;
    }

    .status-badge{
        display:inline-block !important;
        min-width:auto !important;
        padding:4px 8px !important;
        border:1px solid #000 !important;
        background:#fff !important;
        color:#000 !important;
        border-radius:999px !important;
    }

    .muted{
        color:#000 !important;
    }

    @page{
        size:A4 landscape;
        margin:12mm;
    }
}
</style>

<div class="grid">
    <?php if ($msg !== ''): ?>
        <div class="msg ok"><?= h($msg) ?></div>
    <?php endif; ?>

    <?php if ($err !== ''): ?>
        <div class="msg err"><?= h($err) ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="cardHead no-print">
            <div style="font-size:20px">الحضور والانصراف</div>

            <div class="row" style="margin:0">
                <form method="get" class="row" style="margin:0">
                    <input class="input" type="date" name="day" value="<?= h($day) ?>" style="width:220px">
                    <button class="btn ghost" type="submit">عرض</button>
                </form>

                <button type="button" class="btn print-btn" onclick="printAttendanceOnly()">طباعة كشف الحضور</button>
            </div>
        </div>

        <div class="shiftBox no-print">
            <div class="shiftItem">
                <div class="shiftLabel">الفرع</div>
                <div class="shiftValue"><?= h($branchLabel) ?></div>
            </div>

            <div class="shiftItem">
                <div class="shiftLabel">الدوام الرسمي لهذا اليوم</div>
                <div class="shiftValue"><?= h((string)$selectedShift['text']) ?></div>
            </div>

            <div class="shiftItem">
                <div class="shiftLabel">بداية الدوام</div>
                <div class="shiftValue"><?= h((string)$selectedShift['start_label']) ?></div>
            </div>

            <div class="shiftItem">
                <div class="shiftLabel">نهاية الدوام</div>
                <div class="shiftValue"><?= h((string)$selectedShift['end_label']) ?></div>
            </div>
        </div>

        <div class="card no-print" style="margin-bottom:12px">
            <div class="cardHead">
                <div style="font-size:18px">تسجيل عبر QR</div>
                <div class="muted">اكتب الكود أو الصقه هنا</div>
            </div>

            <form method="post" class="row" style="align-items:flex-end;margin:0">
                <input type="hidden" name="action" value="scan_qr">

                <div class="field">
                    <label class="muted">QR Token</label>
                    <input
                        class="input"
                        name="qr_token"
                        id="qrInput"
                        placeholder="امسح أو الصق هنا"
                        autocomplete="off"
                        inputmode="text"
                    >
                </div>

                <div class="field">
                    <label class="muted">ملاحظة</label>
                    <input class="input" name="note" placeholder="اختياري">
                </div>

                <button class="btn" type="submit">تسجيل</button>
            </form>
        </div>

        <?php if ($canManageAttendance): ?>
            <div class="card no-print" style="margin-bottom:12px">
                <div class="cardHead">
                    <div style="font-size:18px">تسجيل يدوي</div>
                    <div class="muted">للإدارة فقط</div>
                </div>

                <form method="post" class="row actions" style="margin:0">
                    <div class="field">
                        <label class="muted">الموظف</label>
                        <select class="select" name="employee_id" required>
                            <option value="">اختر الموظف</option>
                            <?php foreach ($emps as $e): ?>
                                <option value="<?= (int)$e['id'] ?>"><?= h((string)$e['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="field">
                        <label class="muted">ملاحظة</label>
                        <input class="input" type="text" name="note" placeholder="اختياري">
                    </div>

                    <button class="btn" type="submit" name="action" value="checkin">تسجيل دخول</button>
                    <button class="btn ghost" type="submit" name="action" value="checkout">تسجيل خروج</button>
                </form>
            </div>
        <?php endif; ?>

        <div id="attendancePrintArea">
            <div class="print-header">
                <div class="print-company">مجموعة حمدان القانونية</div>
                <div class="print-title">كشف الحضور والانصراف</div>

                <div class="print-meta">
                    <div>الفرع: <?= h($branchLabel) ?></div>
                    <div>التاريخ: <?= h($day) ?></div>
                    <div>الدوام الرسمي: <?= h((string)$selectedShift['text']) ?></div>
                </div>
            </div>

            <div style="overflow:auto">
                <table>
                    <thead>
                        <tr>
                            <th>الموظف</th>
                            <th>الحالة</th>
                            <th>الدوام الرسمي</th>
                            <th>الدخول</th>
                            <th>الخروج</th>
                            <th>ملاحظة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $l): ?>
                            <?php
                                $schedule = attendance_schedule_for_date($branchKey, $day);

                                $statusText = attendance_status_label(
                                    (string)($l['status'] ?? ''),
                                    (string)($l['check_in'] ?? ''),
                                    (string)($l['check_out'] ?? ''),
                                    $schedule,
                                    $day,
                                    (string)($l['leave_type'] ?? ''),
                                    (string)($l['leave_status'] ?? '')
                                );

                                $statusClass = attendance_status_class(
                                    (string)($l['status'] ?? ''),
                                    (string)($l['check_in'] ?? ''),
                                    (string)($l['check_out'] ?? ''),
                                    $schedule,
                                    $day,
                                    (string)($l['leave_type'] ?? ''),
                                    (string)($l['leave_status'] ?? '')
                                );

                                $noteText = attendance_build_note(
                                    (string)($l['note'] ?? ''),
                                    $schedule,
                                    (string)($l['check_in'] ?? ''),
                                    (string)($l['check_out'] ?? ''),
                                    $day,
                                    (string)($l['leave_type'] ?? ''),
                                    (string)($l['leave_status'] ?? '')
                                );
                            ?>
                            <tr>
                                <td><?= h((string)$l['full_name']) ?></td>
                                <td>
                                    <span class="status-badge <?= h($statusClass) ?>">
                                        <?= h($statusText) ?>
                                    </span>
                                </td>
                                <td><?= h((string)$schedule['text']) ?></td>
                                <td><?= h(attendance_display_time((string)($l['check_in'] ?? ''))) ?></td>
                                <td><?= h(attendance_display_time((string)($l['check_out'] ?? ''))) ?></td>
                                <td><?= h($noteText) ?></td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if (!$logs): ?>
                            <tr>
                                <td colspan="6" class="muted">لا يوجد سجلات لهذا اليوم</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($debug): ?>
            <div class="msg no-print" style="margin-top:12px">
                <div class="muted">DEBUG</div>
                <div class="muted" style="direction:ltr;text-align:left">
                    role=<?= h($role) ?>
                    · canManageAttendance=<?= $canManageAttendance ? '1' : '0' ?>
                    · branch_id=<?= (int)$branchId ?>
                    · branchKey=<?= h($branchKey) ?>
                    · user_id=<?= (int)$userId ?>
                    · sessionEmpId=<?= (int)$sessionEmpId ?>
                    · empHasUserId=<?= $empHasUserId ? '1' : '0' ?>
                    · empHasQr1=<?= $empHasQr1 ? '1' : '0' ?>
                    · empHasQr2=<?= $empHasQr2 ? '1' : '0' ?>
                    · leaveTableReady=<?= $leaveTableReady ? '1' : '0' ?>
                    · shift=<?= h((string)$selectedShift['text']) ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
(function () {
    const el = document.getElementById('qrInput');
    if (!el) return;

    el.focus();
    let t = null;

    el.addEventListener('input', function () {
        clearTimeout(t);
        t = setTimeout(() => {
            const v = (this.value || '').trim();
            if (v.length >= 4) {
                this.form.submit();
            }
        }, 250);
    });

    el.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const v = (this.value || '').trim();
            if (v.length >= 4) {
                this.form.submit();
            }
        }
    });
})();
</script>
<script>
function printAttendanceOnly() {
    const area = document.getElementById('attendancePrintArea');
    if (!area) return;

    const printWindow = window.open('', '_blank', 'width=1200,height=900');
    if (!printWindow) {
        alert('تعذر فتح نافذة الطباعة. تأكد من السماح بالنوافذ المنبثقة.');
        return;
    }

    const html = `
    <!doctype html>
    <html lang="ar" dir="rtl">
    <head>
        <meta charset="utf-8">
        <title>طباعة كشف الحضور</title>
        <style>
            @page{
                size:A4 landscape;
                margin:12mm;
            }

            *{
                box-sizing:border-box;
            }

            html,body{
                margin:0;
                padding:0;
                background:#fff;
                color:#000;
                font-family:'Tahoma','Arial',sans-serif;
                direction:rtl;
            }

            body{
                padding:0;
            }

            .print-header{
                display:block !important;
                margin-bottom:14px;
            }

            .print-company{
                text-align:center;
                font-size:16px;
                font-weight:700;
                margin-bottom:6px;
                color:#000;
            }

            .print-title{
                text-align:center;
                font-size:24px;
                font-weight:700;
                margin-bottom:14px;
                color:#000;
            }

            .print-meta{
                display:flex;
                justify-content:space-between;
                gap:12px;
                flex-wrap:wrap;
                margin-bottom:16px;
                color:#000;
                font-size:14px;
            }

            table{
                width:100%;
                border-collapse:collapse;
                min-width:0 !important;
            }

            th, td{
                border:1px solid #000 !important;
                padding:8px !important;
                color:#000 !important;
                background:#fff !important;
                text-align:right !important;
                vertical-align:middle;
                font-size:12px !important;
            }

            th{
                font-weight:700 !important;
            }

            .status-badge{
                display:inline-block !important;
                min-width:auto !important;
                padding:4px 8px !important;
                border:1px solid #000 !important;
                background:#fff !important;
                color:#000 !important;
                border-radius:999px !important;
                font-size:12px !important;
            }

            .muted{
                color:#000 !important;
            }

            .no-print{
                display:none !important;
            }
        </style>
    </head>
    <body>
        ${area.innerHTML}
    </body>
    </html>
    `;

    printWindow.document.open();
    printWindow.document.write(html);
    printWindow.document.close();

    printWindow.onload = function () {
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    };
}

(function () {
    const el = document.getElementById('qrInput');
    if (!el) return;

    el.focus();
    let t = null;

    el.addEventListener('input', function () {
        clearTimeout(t);
        t = setTimeout(() => {
            const v = (this.value || '').trim();
            if (v.length >= 4) {
                this.form.submit();
            }
        }, 250);
    });

    el.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const v = (this.value || '').trim();
            if (v.length >= 4) {
                this.form.submit();
            }
        }
    });
})();
</script>
<?php render_layout_end(); ?>