<?php
// dashboard_employee.php

ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');

if (!file_exists('config.php')) die("Config file missing.");
include 'config.php';

if ($conn->connect_error) die("Database connection error.");
if (!isset($_SESSION['user_id'], $_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    header("Location: login.php"); exit();
}

$employee_id = $_SESSION['user_id'];
$username    = $_SESSION['username'] ?? 'User';
$today       = date('Y-m-d');
$month       = date('Y-m');
$monthStart  = $month . '-01';
$monthEnd    = date('Y-m-t', strtotime($monthStart));

/*
 * ── OFFICE TIMING RULES (NEW, same as the manager dashboard) ──
 * Office hours: 9:30 AM to 6:30 PM.
 *  - Check-in after 09:30:00       -> "Late"
 *  - Check-out at/before 13:00:00  -> "Half Day"
 */
$office_start_time    = '09:30:00';
$office_end_time      = '18:30:00';
$half_day_cutoff_time = '13:00:00';

function tableExists($conn, $table) {
    $t   = $conn->real_escape_string($table);
    $res = $conn->query("SHOW TABLES LIKE '{$t}'");
    return $res && $res->num_rows > 0;
}
function columnExists($conn, $table, $column) {
    $t   = $conn->real_escape_string($table);
    $c   = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
    return $res && $res->num_rows > 0;
}
function ensureColumn($conn, $table, $column, $definition) {
    if (!columnExists($conn, $table, $column)) {
        $conn->query("ALTER TABLE `{$table}` ADD COLUMN `{$column}` {$definition}");
    }
}
/* Helper: classify a daily_reports row into Late / Half Day flags */
function classifyAttendance($login_time, $logout_time, $office_start_time, $half_day_cutoff_time) {
    $is_late = false; $is_half_day = false;
    if (!empty($login_time)) {
        $is_late = date('H:i:s', strtotime($login_time)) > $office_start_time;
    }
    if (!empty($logout_time)) {
        $is_half_day = date('H:i:s', strtotime($logout_time)) <= $half_day_cutoff_time;
    }
    return ['late' => $is_late, 'half_day' => $is_half_day];
}

/* ============================================================
   MONTHLY CL CALCULATION (PART 4)
   Determines, for a given user + calendar month, whether an
   Approved or Pending CL exists, independent of the annual
   leave_balance.balance figure. Handles CL requests that span
   multiple dates / cross month boundaries by only counting the
   portion of the request that actually falls inside the target
   month.
   ============================================================ */
function getMonthlyCLStatus($conn, $user_id, $year, $month) {
    $monthStart = sprintf('%04d-%02d-01', $year, $month);
    $monthEnd   = date('Y-m-t', strtotime($monthStart));

    $sql = "SELECT id, start_date, end_date, status
            FROM leave_requests
            WHERE employee_id = ?
              AND leave_type = 'CL'
              AND status IN ('Approved','Pending')
              AND start_date <= ?
              AND end_date   >= ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iss", $user_id, $monthEnd, $monthStart);
    $stmt->execute();
    $res = $stmt->get_result();

    $approved_found = false;
    $pending_found  = false;
    while ($row = $res->fetch_assoc()) {
        if ($row['status'] === 'Approved') $approved_found = true;
        if ($row['status'] === 'Pending')  $pending_found  = true;
    }
    $stmt->close();

    $used      = $approved_found ? 1 : 0;
    $available = $approved_found ? 0 : 1;
    return [
        'monthly_cl'   => 1,
        'cl_used'      => $used,
        'cl_available' => $available,
        'has_approved' => $approved_found,
        'has_pending'  => $pending_found,
        'blocked'      => ($approved_found || $pending_found),
    ];
}

/* Can this employee apply for a new CL request that touches [start_date, end_date]? */
function canApplyCL($conn, $user_id, $start_date, $end_date) {
    $cursor = strtotime(date('Y-m-01', strtotime($start_date)));
    $endTs  = strtotime(date('Y-m-01', strtotime($end_date)));
    while ($cursor <= $endTs) {
        $y = (int)date('Y', $cursor); $m = (int)date('n', $cursor);
        $status = getMonthlyCLStatus($conn, $user_id, $y, $m);
        if ($status['blocked']) {
            return ['allowed' => false, 'reason' => "CL already Approved/Pending for ".date('F Y', $cursor)];
        }
        $cursor = strtotime('+1 month', $cursor);
    }
    return ['allowed' => true, 'reason' => ''];
}

/* ============================================================
   COMP OFF BALANCE — FINAL APPROVAL DEDUCTION (PART 5)
   Call this the moment a leave_requests row's status becomes the
   system's FINAL "Approved" state. Only deducts for leave_type =
   'Compensatory', only once (guarded by balance_deducted), inside
   a transaction so the flag and the balance move together.
   ============================================================ */
function deductCompOffIfApproved($conn, $leave_request_id) {
    $conn->begin_transaction();
    $stmt = $conn->prepare("SELECT id, employee_id, leave_type, start_date, end_date, status, balance_deducted
                             FROM leave_requests WHERE id = ? FOR UPDATE");
    $stmt->bind_param("i", $leave_request_id);
    $stmt->execute();
    $lr = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$lr || $lr['leave_type'] !== 'Compensatory' || $lr['status'] !== 'Approved' || (int)$lr['balance_deducted'] === 1) {
        $conn->rollback();
        return false;
    }

    $days = (strtotime($lr['end_date']) - strtotime($lr['start_date'])) / 86400 + 1;
    if ($days < 1) $days = 1;
    $year = date('Y', strtotime($lr['start_date']));

    $bstmt = $conn->prepare("SELECT id, balance FROM leave_balance WHERE user_id=? AND leave_type='Compensatory' AND year=? FOR UPDATE");
    $bstmt->bind_param("is", $lr['employee_id'], $year);
    $bstmt->execute();
    $bal = $bstmt->get_result()->fetch_assoc();
    $bstmt->close();

    if (!$bal || (float)$bal['balance'] < $days) {
        $conn->rollback();
        return false;
    }

    $newBal = (float)$bal['balance'] - $days;
    $u1 = $conn->prepare("UPDATE leave_balance SET balance=?, last_updated=NOW() WHERE id=?");
    $u1->bind_param("di", $newBal, $bal['id']);
    $u1->execute(); $u1->close();

    $u2 = $conn->prepare("UPDATE leave_requests SET balance_deducted=1 WHERE id=?");
    $u2->bind_param("i", $leave_request_id);
    $u2->execute(); $u2->close();

    $conn->commit();
    return true;
}

/* Restore Comp Off balance if an already-approved+deducted request is later cancelled/reversed. */
function restoreCompOffIfReversed($conn, $leave_request_id) {
    $conn->begin_transaction();
    $stmt = $conn->prepare("SELECT id, employee_id, leave_type, start_date, end_date, status, balance_deducted
                             FROM leave_requests WHERE id = ? FOR UPDATE");
    $stmt->bind_param("i", $leave_request_id);
    $stmt->execute();
    $lr = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$lr || $lr['leave_type'] !== 'Compensatory' || (int)$lr['balance_deducted'] !== 1) {
        $conn->rollback();
        return false;
    }
    if (!in_array($lr['status'], ['Cancelled','Rejected','Reversed'])) {
        $conn->rollback();
        return false;
    }

    $days = (strtotime($lr['end_date']) - strtotime($lr['start_date'])) / 86400 + 1;
    if ($days < 1) $days = 1;
    $year = date('Y', strtotime($lr['start_date']));

    $bstmt = $conn->prepare("SELECT id, balance FROM leave_balance WHERE user_id=? AND leave_type='Compensatory' AND year=? FOR UPDATE");
    $bstmt->bind_param("is", $lr['employee_id'], $year);
    $bstmt->execute();
    $bal = $bstmt->get_result()->fetch_assoc();
    $bstmt->close();

    if ($bal) {
        $newBal = (float)$bal['balance'] + $days;
        $u1 = $conn->prepare("UPDATE leave_balance SET balance=?, last_updated=NOW() WHERE id=?");
        $u1->bind_param("di", $newBal, $bal['id']);
        $u1->execute(); $u1->close();
    }

    $u2 = $conn->prepare("UPDATE leave_requests SET balance_deducted=0 WHERE id=?");
    $u2->bind_param("i", $leave_request_id);
    $u2->execute(); $u2->close();

    $conn->commit();
    return true;
}

$ensure = [
    ['users','offer_accepted',          "VARCHAR(20) DEFAULT NULL"],
    ['users','offer_accepted_at',       "DATETIME DEFAULT NULL"],
    ['users','details_accepted',        "VARCHAR(20) DEFAULT NULL"],
    ['users','responsibilities_accepted',"VARCHAR(20) DEFAULT NULL"],
    ['users','emergency_contact_name',  "VARCHAR(100) DEFAULT NULL"],
    ['users','emergency_contact_phone', "VARCHAR(20) DEFAULT NULL"],
    ['daily_reports','logout_photo_path', "VARCHAR(255) DEFAULT NULL"],
    /* PART 6: DATABASE SAFETY — new columns, guarded against duplicates */
    ['daily_reports','daily_working_hours', "DECIMAL(5,2) NULL DEFAULT NULL"],
    ['leave_requests','balance_deducted', "TINYINT(1) NOT NULL DEFAULT 0"],
];
foreach ($ensure as $e) ensureColumn($conn, $e[0], $e[1], $e[2]);

if (!tableExists($conn,'monthly_working_hours')) {
    $conn->query("CREATE TABLE IF NOT EXISTS monthly_working_hours (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        year INT NOT NULL,
        month INT NOT NULL,
        total_working_hours DECIMAL(7,2) NOT NULL DEFAULT 0,
        total_working_minutes INT NOT NULL DEFAULT 0,
        total_working_days INT NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_user_year_month (user_id, year, month)
    ) ENGINE=InnoDB");
}

/* ── PHOTO UPLOAD ── */
$photo_upload_msg  = '';
$photo_upload_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_photo'])) {
    $file    = $_FILES['profile_photo'];
    $allowed = ['image/jpeg','image/jpg','image/png','image/gif','image/webp'];
    $maxSize = 5 * 1024 * 1024;

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $photo_upload_msg = 'Upload failed. Please try again.'; $photo_upload_type = 'error';
    } elseif (!in_array($file['type'], $allowed)) {
        $photo_upload_msg = 'Only JPG, PNG, GIF, WEBP allowed.'; $photo_upload_type = 'error';
    } elseif ($file['size'] > $maxSize) {
        $photo_upload_msg = 'File too large. Max 5MB.'; $photo_upload_type = 'error';
    } else {
        $upload_folder = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/uploads/';
        if (!is_dir($upload_folder)) @mkdir($upload_folder, 0775, true);
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'profile_' . $employee_id . '_' . time() . '.' . $ext;
        $dest = $upload_folder . $filename;
        if (move_uploaded_file($file['tmp_name'], $dest)) {
            $stmt = $conn->prepare("UPDATE users SET photo = ? WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("ss", $filename, $employee_id);
                if ($stmt->execute()) { $photo_upload_msg = 'Profile photo updated!'; $photo_upload_type = 'success'; }
                else { $photo_upload_msg = 'Photo saved but DB update failed.'; $photo_upload_type = 'error'; }
                $stmt->close();
            }
        } else { $photo_upload_msg = 'Could not save file. Check permissions.'; $photo_upload_type = 'error'; }
    }
}

/* ── PASSWORD CHANGE ── */
$pwd_change_msg  = '';
$pwd_change_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['current_password'], $_POST['new_password'], $_POST['confirm_password'])) {
    $current_password = $_POST['current_password'];
    $new_password     = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    $stmt_pwd = $conn->prepare("SELECT password FROM users WHERE id = ?");
    if ($stmt_pwd) {
        $stmt_pwd->bind_param("s", $employee_id);
        $stmt_pwd->execute();
        $stmt_pwd->bind_result($stored_hash);
        $stmt_pwd->fetch();
        $stmt_pwd->close();

        if (!password_verify($current_password, $stored_hash)) {
            $pwd_change_msg = 'Current password is incorrect.'; $pwd_change_type = 'error';
        } elseif (strlen($new_password) < 8) {
            $pwd_change_msg = 'New password must be at least 8 characters.'; $pwd_change_type = 'error';
        } elseif ($new_password !== $confirm_password) {
            $pwd_change_msg = 'Passwords do not match.'; $pwd_change_type = 'error';
        } elseif (password_verify($new_password, $stored_hash)) {
            $pwd_change_msg = 'New password must differ from current.'; $pwd_change_type = 'error';
        } else {
            $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt_upd = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt_upd) {
                $stmt_upd->bind_param("ss", $new_hash, $employee_id);
                if ($stmt_upd->execute()) { $pwd_change_msg = 'Password changed successfully!'; $pwd_change_type = 'success'; }
                else { $pwd_change_msg = 'Failed to update. Please try again.'; $pwd_change_type = 'error'; }
                $stmt_upd->close();
            }
        }
    }
}

/* ── ATTENDANCE CHECK-IN (unchanged from before) ── */
$attendance_msg  = '';
$attendance_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'attendance_checkin') {
    if (empty($_POST['photo_data'])) {
        $attendance_msg = "Selfie photo is required to check in."; $attendance_type = 'error';
    } else {
        $dir = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/uploads/attendance/';
        if (!is_dir($dir)) @mkdir($dir, 0775, true);
        $filename = 'checkin_'.$employee_id.'_'.date('Ymd_His').'.jpg';
        $dest = $dir.$filename;
        $raw = base64_decode(str_replace(['data:image/jpeg;base64,',' '],['','+'],$_POST['photo_data']));

        if ($raw !== false && file_put_contents($dest, $raw) !== false) {
            $rel_photo   = 'uploads/attendance/'.$filename;
            $lat         = ($_POST['lat'] ?? '') !== '' ? $_POST['lat'] : null;
            $lng         = ($_POST['lng'] ?? '') !== '' ? $_POST['lng'] : null;
            $loc_type    = $_POST['location_type'] ?? 'Office';
            $client_name = trim($_POST['client_name'] ?? '');

            $loc_enum_map = [
                'Office'         => 'Corporate Office',
                'Client Visit'   => 'Client Office',
                'Field Work'     => 'Corporate Office',
                'Work From Home' => 'Work from Home',
            ];
            $location_enum  = $loc_enum_map[$loc_type] ?? 'Corporate Office';
            $name_of_client = $client_name !== '' ? $client_name : 'N/A';
            $morning_note   = 'Checked in via dashboard';
            $now_dt         = date('Y-m-d H:i:s');

            $stmt = $conn->prepare(
                "INSERT INTO daily_reports
                    (user_id, report_date, Location, `Name of the Client`, Morning,
                     location_type, client_name, latitude, longitude, photo_path,
                     login_time, approval_status)
                 VALUES (?,?,?,?,?,?,?,?,?,?,?, 'Pending')
                 ON DUPLICATE KEY UPDATE
                    Location             = VALUES(Location),
                    `Name of the Client` = VALUES(`Name of the Client`),
                    location_type        = VALUES(location_type),
                    client_name           = VALUES(client_name),
                    latitude              = VALUES(latitude),
                    longitude             = VALUES(longitude),
                    photo_path            = VALUES(photo_path),
                    login_time            = VALUES(login_time)"
            );
            $stmt->bind_param(
                "sssssssddss",
                $employee_id, $today, $location_enum, $name_of_client, $morning_note,
                $loc_type, $client_name, $lat, $lng, $rel_photo, $now_dt
            );
            $stmt->execute(); $stmt->close();
            $attendance_msg = "Checked in successfully!"; $attendance_type = 'success';
        } else {
            $attendance_msg = "Failed to save check-in photo."; $attendance_type = 'error';
        }
    }
}

/* ── ATTENDANCE CHECK-OUT (UPDATED) ──
   Adds, inside a single transaction:
     1. Fetch today's login_time.
     2. Save logout_time + geolocation + checkout selfie (unchanged).
     3. DAILY WORKING HOURS CALCULATION — compute decimal hours from
        login_time -> logout_time on the PHP backend.
     4. MONTHLY WORKING HOURS UPDATE — recalculate the whole month
        from daily_reports and upsert monthly_working_hours via
        INSERT ... ON DUPLICATE KEY UPDATE (unique per user/year/month). */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'attendance_checkout') {
    if (empty($_POST['photo_data'])) {
        $attendance_msg = "Selfie photo is required to check out."; $attendance_type = 'error';
    } else {
        $dir = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/uploads/attendance/';
        if (!is_dir($dir)) @mkdir($dir, 0775, true);
        $filename = 'checkout_'.$employee_id.'_'.date('Ymd_His').'.jpg';
        $dest = $dir.$filename;
        $raw = base64_decode(str_replace(['data:image/jpeg;base64,',' '],['','+'],$_POST['photo_data']));

        if ($raw !== false && file_put_contents($dest, $raw) !== false) {
            $rel_photo = 'uploads/attendance/'.$filename;
            $lat = ($_POST['lat'] ?? '') !== '' ? $_POST['lat'] : null;
            $lng = ($_POST['lng'] ?? '') !== '' ? $_POST['lng'] : null;
            $now_dt = date('Y-m-d H:i:s');

            $conn->begin_transaction();
            try {
                // 1. Fetch today's login_time first (needed to compute hours).
                $lstmt = $conn->prepare("SELECT login_time FROM daily_reports WHERE user_id=? AND report_date=? FOR UPDATE");
                $lstmt->bind_param("ss", $employee_id, $today);
                $lstmt->execute();
                $todayRow = $lstmt->get_result()->fetch_assoc();
                $lstmt->close();

                if (!$todayRow || empty($todayRow['login_time'])) {
                    throw new Exception('No check-in found for today.');
                }

                // DAILY WORKING HOURS CALCULATION
                $login_ts  = strtotime($todayRow['login_time']);
                $logout_ts = strtotime($now_dt);
                $diff_secs = max(0, $logout_ts - $login_ts);
                $daily_working_hours = round($diff_secs / 3600, 2); // e.g. 8.50

                // 2. Save logout_time, geolocation, checkout selfie, and computed hours.
                $stmt = $conn->prepare("UPDATE daily_reports SET logout_time=?, logout_latitude=?, logout_longitude=?, logout_photo_path=?, daily_working_hours=? WHERE user_id=? AND report_date=?");
                $stmt->bind_param("sddsdss", $now_dt, $lat, $lng, $rel_photo, $daily_working_hours, $employee_id, $today);
                $stmt->execute(); $stmt->close();

                // MONTHLY WORKING HOURS UPDATE
                $curYear  = (int)date('Y', $logout_ts);
                $curMonth = (int)date('n', $logout_ts);
                $mStart   = sprintf('%04d-%02d-01', $curYear, $curMonth);
                $mEnd     = date('Y-m-t', strtotime($mStart));

                $mstmt = $conn->prepare("SELECT login_time, logout_time, daily_working_hours FROM daily_reports WHERE user_id=? AND report_date BETWEEN ? AND ?");
                $mstmt->bind_param("sss", $employee_id, $mStart, $mEnd);
                $mstmt->execute();
                $mres = $mstmt->get_result();

                $totalHoursDecimal = 0.0;
                $totalWorkingDays  = 0;
                while ($mrow = $mres->fetch_assoc()) {
                    if (!empty($mrow['login_time']) && !empty($mrow['logout_time'])) {
                        $totalWorkingDays++;
                        if ($mrow['daily_working_hours'] !== null) {
                            $totalHoursDecimal += (float)$mrow['daily_working_hours'];
                        } else {
                            $diff = max(0, strtotime($mrow['logout_time']) - strtotime($mrow['login_time']));
                            $totalHoursDecimal += round($diff / 3600, 2);
                        }
                    }
                }
                $mstmt->close();

                $totalWorkingMinutes = (int)round($totalHoursDecimal * 60);

                // INSERT ... ON DUPLICATE KEY UPDATE — relies on the
                // UNIQUE KEY (user_id, year, month); never duplicates.
                $ustmt = $conn->prepare(
                    "INSERT INTO monthly_working_hours
                        (user_id, year, month, total_working_hours, total_working_minutes, total_working_days, created_at, updated_at)
                     VALUES (?,?,?,?,?,?,NOW(),NOW())
                     ON DUPLICATE KEY UPDATE
                        total_working_hours   = VALUES(total_working_hours),
                        total_working_minutes = VALUES(total_working_minutes),
                        total_working_days    = VALUES(total_working_days),
                        updated_at            = NOW()"
                );
                $ustmt->bind_param("siidii", $employee_id, $curYear, $curMonth, $totalHoursDecimal, $totalWorkingMinutes, $totalWorkingDays);
                $ustmt->execute(); $ustmt->close();

                $conn->commit();
                $attendance_msg = "Checked out successfully!"; $attendance_type = 'success';
            } catch (Exception $e) {
                $conn->rollback();
                $attendance_msg = "Checkout failed: ".$e->getMessage(); $attendance_type = 'error';
            }
        } else {
            $attendance_msg = "Failed to save check-out photo."; $attendance_type = 'error';
        }
    }
}

/* ── FETCH USER DATA ── */
$required_columns = ['id','username','email','role','status'];
$optional_columns = [
    'responsibilities','responsibilities_accepted','mobileno','division','designation','position',
    'date_of_joining','resignation_date','rejoin_date','basic_salary','role_id','address',
    'pancard','aadharcard','photo','marital_status','anniversary_date','gender','date_of_birth',
    'mother_name','father_name','spouse_name','no_of_children','qualification','previous_experience',
    'company_name','total_experience_years','previous_salary','uan_no','bloodgroup','esic_no',
    'bank_name','account_number','ifsc_code','first_name','last_name','level','performance',
    'appointment_type','location','reporting_manager','details_accepted','kpi','kpi_status',
    'offer_accepted','offer_accepted_at','emergency_contact_name','emergency_contact_phone',
];

$existing_columns = [];
foreach (array_merge($required_columns, $optional_columns) as $col) {
    if (columnExists($conn, 'users', $col)) $existing_columns[] = $col;
}

$user = [];
if (!empty($existing_columns)) {
    $sql  = "SELECT " . implode(', ', $existing_columns) . " FROM users WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt) { $stmt->bind_param("s", $employee_id); $stmt->execute(); $user = $stmt->get_result()->fetch_assoc() ?? []; $stmt->close(); }
}
$u = fn($k, $d = '') => $user[$k] ?? $d;

$document_root    = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
$upload_dir_rel   = 'uploads/';
$base_url         = '/' . trim($upload_dir_rel, '/') . '/';
$default_photo    = 'default-profile.png';
$default_photo_url= $base_url . $default_photo;

/*
 * FIX: no more "blink" for missing photos.
 * We now check on the SERVER whether the photo file actually exists on
 * disk and only ever output a valid <img src>, instead of always
 * pointing at the user's (possibly missing) photo and relying on a
 * client-side onerror swap, which is what caused the visible flash.
 */
if (!empty($user['photo']) && file_exists($document_root.'/uploads/'.$user['photo'])) {
    $photo_url = $base_url . ltrim($user['photo'], '/') . '?t=' . time();
} else {
    $photo_url = $default_photo_url;
}

/* ── MY ATTENDANCE TODAY (NEW — daily_reports based) ── */
$stmt = $conn->prepare("SELECT * FROM daily_reports WHERE user_id=? AND report_date=?");
$stmt->bind_param("ss",$employee_id,$today); $stmt->execute();
$my_today = $stmt->get_result()->fetch_assoc() ?? []; $stmt->close();

$my_checked_in  = !empty($my_today['login_time']);
$my_checked_out = !empty($my_today['logout_time']);
$my_today_flags = classifyAttendance($my_today['login_time'] ?? null, $my_today['logout_time'] ?? null, $office_start_time, $half_day_cutoff_time);

/* Monthly roll-up: how many check-ins / check-outs / late / half-days this month */
$stmt = $conn->prepare("SELECT report_date, login_time, logout_time FROM daily_reports WHERE user_id=? AND report_date BETWEEN ? AND ?");
$stmt->bind_param("sss",$employee_id,$monthStart,$monthEnd); $stmt->execute();
$res = $stmt->get_result();
$my_checkin_count = 0; $my_checkout_count = 0; $my_late_count = 0; $my_halfday_count = 0;
while ($row = $res->fetch_assoc()) {
    $flags = classifyAttendance($row['login_time'], $row['logout_time'], $office_start_time, $half_day_cutoff_time);
    if (!empty($row['login_time']))  { $my_checkin_count++;  if ($flags['late'])     $my_late_count++; }
    if (!empty($row['logout_time'])) { $my_checkout_count++; if ($flags['half_day']) $my_halfday_count++; }
}
$stmt->close();

/* MONTHLY WORKING HOURS (NEW) — this employee's current-month summary */
$mwh_stmt = $conn->prepare("SELECT total_working_hours, total_working_minutes, total_working_days FROM monthly_working_hours WHERE user_id=? AND year=? AND month=?");
$mwh_year  = (int)date('Y', strtotime($monthStart));
$mwh_month = (int)date('n', strtotime($monthStart));
$mwh_stmt->bind_param("sii", $employee_id, $mwh_year, $mwh_month);
$mwh_stmt->execute();
$my_monthly_hours = $mwh_stmt->get_result()->fetch_assoc();
$mwh_stmt->close();

/* MONTHLY CL CALCULATION (NEW) */
$my_cl_status = getMonthlyCLStatus($conn, $employee_id, $mwh_year, $mwh_month);

/* ── PAYSLIPS ── */
$payslip_count      = 0;
$payroll_has_status = false;
$result_payslips    = null;
if (tableExists($conn, 'payroll')) {
    $payroll_has_status = columnExists($conn, 'payroll', 'status');
    $sql  = "SELECT id, month, grand_total, " . ($payroll_has_status ? "status" : "NULL AS status") .
            " FROM payroll WHERE emp_id = ? ORDER BY month DESC LIMIT 12";
    $stmt = $conn->prepare($sql);
    if ($stmt) { $stmt->bind_param("s", $employee_id); $stmt->execute(); $result_payslips = $stmt->get_result(); $payslip_count = $result_payslips->num_rows; $stmt->close(); }
}

/* ── LEAVE BALANCE (PART 3 — always show CL / SL / Comp Off, defaulting to 0) ──
   Rather than only rendering whatever rows happen to exist in
   leave_balance (which hid Comp Off — and would equally hide CL or SL
   for a brand-new employee before their first row is seeded), we now
   always render all three canonical leave types, defaulting any
   missing one to a 0 balance. This is more robust than relying on a
   one-off SQL seed and won't silently drop a type again in future. */
$leave_balance_map = ['CL' => 0, 'SL' => 0, 'Compensatory' => 0];
if (tableExists($conn, 'leave_balance')) {
    $stmt = $conn->prepare("SELECT leave_type, balance FROM leave_balance WHERE user_id = ?");
    if ($stmt) {
        $stmt->bind_param("s", $employee_id); $stmt->execute(); $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $leave_balance_map[$row['leave_type']] = (int)$row['balance'];
        }
        $stmt->close();
    }
}
// Preserve any other custom leave types too (in case more exist beyond CL/SL/Compensatory)
$leave_balance_rows = [];
foreach ($leave_balance_map as $type => $bal) {
    $leave_balance_rows[] = ['leave_type' => $type, 'balance' => $bal];
}

/* ── HOLIDAYS ── */
$holiday_rows = [];
if (tableExists($conn, 'company_holidays')) {
    $stmt  = $conn->prepare("SELECT holiday_date, name, location, is_optional FROM company_holidays WHERE holiday_date >= ? ORDER BY holiday_date ASC LIMIT 10");
    if ($stmt) { $stmt->bind_param("s", $today); $stmt->execute(); $res = $stmt->get_result(); while ($row = $res->fetch_assoc()) $holiday_rows[] = $row; $stmt->close(); }
}

/* ── DOCUMENTS ── */
$all_docs   = [];
$total_docs = 0;
if (tableExists($conn, 'documents') && tableExists($conn, 'document_status')) {
    $stmt_docs = $conn->prepare("SELECT d.id, d.title, MAX(ds.status) AS status FROM documents d LEFT JOIN document_status ds ON d.id = ds.document_id AND ds.employee_id = ? GROUP BY d.id, d.title");
    if ($stmt_docs) { $stmt_docs->bind_param("s", $employee_id); $stmt_docs->execute(); $all_docs = $stmt_docs->get_result()->fetch_all(MYSQLI_ASSOC); $total_docs = count($all_docs); $stmt_docs->close(); }
}

function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>MPC · Employee Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#fff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:250px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:12px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 12px rgba(15,23,42,.07);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%;overflow-x:hidden}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}

/* ═══ SIDEBAR ═══ */
.sidebar{
  width:var(--sidebar-w);background:var(--sidebar-bg);
  position:fixed;inset:0 auto 0 0;z-index:300;
  display:flex;flex-direction:column;overflow-y:auto;
  transition:transform .28s cubic-bezier(.4,0,.2,1);
  scrollbar-width:none;
}
.sidebar::-webkit-scrollbar{display:none}
.sidebar-brand{padding:18px 16px 12px;display:flex;align-items:center;gap:9px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:4px}
.brand-logo{width:30px;height:30px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:7px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:13px;flex-shrink:0}
.brand-name{font-size:13px;font-weight:700;color:#fff}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.6px;text-transform:uppercase}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:10px 16px 3px}
.nav-item{list-style:none}
.nav-link-s{display:flex;align-items:center;gap:8px;padding:8px 12px;margin:1px 6px;border-radius:7px;color:rgba(255,255,255,.6);text-decoration:none;font-size:12.5px;font-weight:500;transition:all .15s}
.nav-link-s:hover{background:rgba(255,255,255,.07);color:#fff;text-decoration:none}
.nav-link-s.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link-s i{width:15px;text-align:center;font-size:12px;flex-shrink:0}
.nav-link-s.danger{color:#f87171}.nav-link-s.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:10px 6px;border-top:1px solid rgba(255,255,255,.06)}
.sidebar-user-info{display:flex;align-items:center;gap:9px;padding:9px 12px;margin:0 6px 3px;border-radius:7px;background:rgba(255,255,255,.04)}
.sidebar-avatar-img{width:28px;height:28px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,.2);flex-shrink:0}
.sidebar-uname{font-size:11.5px;font-weight:600;color:rgba(255,255,255,.85);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sidebar-role{font-size:9px;color:rgba(255,255,255,.35);text-transform:uppercase;letter-spacing:.8px}

/* ═══ OVERLAY ═══ */
.sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:290;backdrop-filter:blur(2px);opacity:0;transition:opacity .28s}
.sidebar-overlay.active{display:block;opacity:1}

/* ═══ CONTENT ═══ */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column}

/* ═══ TOPBAR ═══ */
.topbar{
  height:52px;background:var(--surface);border-bottom:1px solid var(--border);
  display:flex;align-items:center;gap:10px;padding:0 14px;
  position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border);
}
.hamburger-btn{
  width:34px;height:34px;border-radius:7px;border:1px solid var(--border);
  background:transparent;display:flex;align-items:center;justify-content:center;
  cursor:pointer;color:var(--ink-2);font-size:14px;flex-shrink:0;transition:background .15s;
}
.hamburger-btn:hover{background:var(--bg)}
.topbar-title{font-size:13px;font-weight:600;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}
.topbar-right{display:flex;align-items:center;gap:6px;flex-shrink:0}
.topbar-avatar{
  width:32px;height:32px;border-radius:50%;object-fit:cover;
  border:2px solid var(--accent-2);cursor:pointer;flex-shrink:0;
}
.topbar-logout-btn{
  display:flex;align-items:center;gap:5px;
  padding:5px 10px;border-radius:7px;
  background:#fee2e2;color:#dc2626;
  border:1px solid #fecaca;
  font-size:11.5px;font-weight:700;
  text-decoration:none;cursor:pointer;
  transition:all .15s;white-space:nowrap;
}
.topbar-logout-btn:hover{background:#dc2626;color:#fff;border-color:#dc2626;text-decoration:none}
.topbar-logout-btn i{font-size:11px}

/* ═══ PAGE ═══ */
.page{padding:12px;flex:1;max-width:100%}
.page-header{margin-bottom:12px;padding:12px 14px;background:var(--surface);border-radius:var(--radius);border:1px solid var(--border);box-shadow:var(--shadow)}
.page-title{font-size:16px;font-weight:700;color:var(--ink);letter-spacing:-.3px}
.page-subtitle{font-size:11px;color:var(--muted);margin-top:2px;text-transform:uppercase;letter-spacing:.4px}

/* ═══ QUICK ACCESS GRID ═══ */
.quick-grid{
  display:grid;
  grid-template-columns:repeat(5,1fr);
  gap:8px;
  margin-bottom:12px;
}
.quick-card{
  background:var(--surface);border:1px solid var(--border);border-radius:10px;
  padding:10px 4px 8px;text-align:center;color:var(--ink-2);text-decoration:none;
  box-shadow:var(--shadow);transition:all .2s;
  display:flex;flex-direction:column;align-items:center;gap:5px;
}
.quick-card:hover{transform:translateY(-2px);box-shadow:0 4px 16px rgba(15,23,42,.12);color:var(--ink);text-decoration:none}
.quick-card:active{transform:scale(.96)}
.qc-icon{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px}
.qc-title{font-size:9.5px;font-weight:700;line-height:1.2;color:var(--ink-2)}
.qc-icon.indigo{background:#ede9fe;color:#4f46e5}.qc-icon.cyan{background:#cffafe;color:#0891b2}
.qc-icon.rose{background:#ffe4e6;color:#e11d48}.qc-icon.emerald{background:#d1fae5;color:#059669}
.qc-icon.blue{background:#dbeafe;color:#1d4ed8}.qc-icon.amber{background:#fef3c7;color:#d97706}
.qc-icon.pink{background:#fce7f3;color:#db2777}.qc-icon.orange{background:#ffedd5;color:#ea580c}
.qc-icon.purple{background:#f3e8ff;color:#7c3aed}

/* ═══ DASH CARD ═══ */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:12px;overflow:hidden}
.dash-card-header{padding:11px 14px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border);flex-wrap:wrap;gap:6px}
.dash-card-title{font-size:12.5px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:6px}
.dash-card-title i{color:var(--accent);font-size:11px}
.dash-card-body{padding:12px}
.dash-card-body.p0{padding:0}

/* ═══ TWO COL ═══ */
.two-col{display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:start}

/* ═══ INFO ROWS ═══ */
.info-row{display:flex;gap:6px;padding:7px 12px;border-bottom:1px solid var(--border);align-items:flex-start}
.info-row:last-child{border-bottom:none}
.info-label{font-size:10px;font-weight:600;color:var(--muted);min-width:110px;flex-shrink:0;text-transform:uppercase;letter-spacing:.3px;padding-top:1px}
.info-value{font-size:12.5px;color:var(--ink-2);flex:1;word-break:break-word}

/* ═══ ACCORDION ═══ */
.acc-section{border:1px solid var(--border);border-radius:9px;overflow:hidden;margin-bottom:7px;background:#fff}
.acc-header{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;cursor:pointer;background:#f8fafc;user-select:none;transition:background .15s;gap:8px;-webkit-tap-highlight-color:transparent}
.acc-header:hover{background:#f1f5f9}
.acc-header.open{background:#ede9fe;border-bottom:1px solid #d4d0f7}
.acc-header-left{display:flex;align-items:center;gap:8px}
.acc-icon{width:26px;height:26px;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:11px;flex-shrink:0}
.acc-title{font-size:12.5px;font-weight:700;color:var(--ink)}
.acc-subtitle{font-size:10px;color:var(--muted);margin-top:1px}
.acc-chevron{width:20px;height:20px;border-radius:5px;background:#e2e8f0;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:transform .25s,background .15s}
.acc-header.open .acc-chevron{transform:rotate(180deg);background:#c7d2fe}
.acc-chevron i{font-size:8px;color:var(--ink-2)}
.acc-body{display:none;border-top:1px solid var(--border)}
.acc-body.open{display:block;animation:slideDown .2s ease}
@keyframes slideDown{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}

/* ═══ PHOTO UPLOAD ═══ */
.photo-upload-wrap{padding:12px}
.photo-area{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}
.profile-photo-lg{width:64px;height:64px;border-radius:50%;object-fit:cover;border:3px solid var(--accent-2);box-shadow:0 3px 10px rgba(0,0,0,.12);flex-shrink:0}
.photo-controls{flex:1;min-width:140px}
.photo-drop-zone{border:2px dashed var(--border);border-radius:8px;padding:10px 12px;text-align:center;background:#fafbfc;cursor:pointer;transition:all .2s;position:relative}
.photo-drop-zone:hover,.photo-drop-zone.drag-over{border-color:var(--accent);background:#f5f3ff}
.photo-drop-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.photo-drop-zone .dz-icon{font-size:18px;color:var(--muted);margin-bottom:4px}
.photo-drop-zone .dz-text{font-size:11.5px;color:var(--muted);font-weight:500}
.photo-drop-zone .dz-hint{font-size:10px;color:#94a3b8;margin-top:2px}
.photo-preview-wrap{margin-top:7px;display:none}
.upload-btn{display:inline-flex;align-items:center;gap:5px;padding:7px 14px;background:var(--accent);color:#fff;border:none;border-radius:7px;font-size:12px;font-weight:600;cursor:pointer;transition:background .15s;margin-top:7px;font-family:'DM Sans',sans-serif}
.upload-btn:hover{background:#3730a3}
.upload-btn:disabled{background:#94a3b8;cursor:not-allowed}
.upload-alert{padding:7px 11px;border-radius:7px;font-size:12px;font-weight:600;margin-top:7px;display:flex;align-items:center;gap:6px}
.upload-alert.success{background:#d1fae5;color:#065f46}
.upload-alert.error{background:#fee2e2;color:#991b1b}

/* ═══ PASSWORD ═══ */
.pwd-input-wrap{position:relative}
.pwd-input-wrap input{width:100%;padding:8px 36px 8px 11px;border:1.5px solid var(--border);border-radius:7px;font-size:12.5px;color:var(--ink);background:#fafbfc;outline:none;transition:border .15s;font-family:'DM Sans',sans-serif}
.pwd-input-wrap input:focus{border-color:var(--accent)}
.pwd-toggle-btn{position:absolute;right:9px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--muted);cursor:pointer;font-size:12px;padding:0}
.pwd-field-label{display:block;font-size:10.5px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;margin-bottom:4px}
.pwd-field-label span{color:var(--red)}

/* ═══ BADGES ═══ */
.badge-custom{display:inline-flex;align-items:center;gap:3px;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:600;white-space:nowrap}
.badge-success{background:#d1fae5;color:#065f46}.badge-warning{background:#fef3c7;color:#92400e}
.badge-danger{background:#fee2e2;color:#991b1b}.badge-purple{background:#ede9fe;color:#5b21b6}
.badge-blue{background:#dbeafe;color:#1e40af}.badge-cyan{background:#cffafe;color:#155e75}

/* ═══ TABLE ═══ */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.dash-table{width:100%;border-collapse:collapse;font-size:12px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:9.5px;text-transform:uppercase;letter-spacing:.6px;padding:8px 10px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:9px 10px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}
.tbl-wrap-scroll{max-height:240px;overflow-y:auto}

/* ═══ EMPTY ═══ */
.empty-state{text-align:center;padding:24px 16px;color:var(--muted)}
.empty-state i{font-size:24px;display:block;margin-bottom:7px;opacity:.25}
.empty-state p{font-size:12px}

/* ═══ DOC ITEM ═══ */
.doc-item{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);gap:6px}
.doc-item:last-child{border-bottom:none}

/* ═══ LEAVE CARDS ═══ */
.leave-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(80px,1fr));gap:8px}
.leave-card{border-radius:9px;padding:10px 6px;text-align:center}
.leave-card-type{font-size:9px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;margin-bottom:2px}
.leave-card-num{font-size:22px;font-weight:800;line-height:1}
.leave-card-label{font-size:9px;opacity:.7;margin-top:1px}

/* ═══ PROFILE HEADER IN CARD ═══ */
.profile-header{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:14px;padding-bottom:14px;border-bottom:1px solid var(--border)}
.profile-header-avatar{width:64px;height:64px;border-radius:50%;object-fit:cover;border:3px solid var(--accent-2);box-shadow:0 3px 10px rgba(0,0,0,.12);flex-shrink:0}
.profile-header-name{font-size:15px;font-weight:700;color:var(--ink)}
.profile-header-email{font-size:11px;color:var(--muted);margin-top:2px}
.profile-header-meta{font-size:11px;color:var(--ink-2);margin-top:3px;display:flex;align-items:center;gap:4px}

/* ═══ ATTENDANCE STATUS TRACK (NEW) ═══ */
.status-track{display:flex;align-items:center;gap:0;margin-bottom:16px}
.status-step{flex:1;text-align:center;position:relative}
.status-step::before{content:'';position:absolute;top:15px;left:50%;right:-50%;height:2px;background:var(--border);z-index:0}
.status-step:last-child::before{display:none}
.step-dot{width:30px;height:30px;border-radius:50%;border:2px solid var(--border);background:var(--surface);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;margin:0 auto 5px;position:relative;z-index:1;transition:all .2s}
.step-dot.done{background:var(--green);border-color:var(--green);color:#fff}
.step-dot.active{background:var(--accent);border-color:var(--accent);color:#fff;box-shadow:0 0 0 4px rgba(79,70,229,.15)}
.step-dot.late{background:var(--amber);border-color:var(--amber);color:#fff}
.step-label{font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px}
.step-time{font-size:10.5px;color:var(--ink-2);margin-top:2px}

/* ═══ CAMERA (NEW) ═══ */
.camera-wrap{border-radius:var(--radius-sm);overflow:hidden;background:#1e293b;position:relative;margin-bottom:12px;min-height:200px;display:flex;align-items:center;justify-content:center}
#empAttVideo{width:100%;max-height:260px;object-fit:cover;display:block;border-radius:var(--radius-sm)}
#empAttCanvas{display:none}
#empAttPreview{width:100%;max-height:200px;object-fit:cover;border-radius:var(--radius-sm);display:none;margin-bottom:10px;box-shadow:var(--shadow)}
.camera-overlay{position:absolute;top:10px;right:10px;background:rgba(0,0,0,.55);color:#fff;font-size:10px;font-weight:600;padding:3px 9px;border-radius:20px;letter-spacing:.5px}
.camera-loading{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:rgba(255,255,255,.7);font-size:12px;font-weight:500}
.camera-loading i{font-size:22px;animation:spin .8s linear infinite}
.camera-error-box{display:none;flex-direction:column;align-items:center;justify-content:center;padding:22px 16px;background:#fff7ed;border:2px dashed #fed7aa;border-radius:var(--radius-sm);margin-bottom:12px;text-align:center;gap:7px}
.camera-error-box.show{display:flex}
.camera-error-box i{font-size:26px;color:#f97316}
.camera-error-box p{font-size:11.5px;color:#7c2d12;line-height:1.5;max-width:260px}
.loc-status{display:none;align-items:center;gap:7px;padding:9px 12px;border-radius:var(--radius-sm);margin-bottom:12px;font-size:12px;font-weight:500}
.loc-status.getting{display:flex;background:#ede9fe;color:#5b21b6}
.loc-status.got{display:flex;background:#d1fae5;color:#065f46}
.loc-status.failed{display:flex;background:#fee2e2;color:#991b1b}
.loading-overlay{display:none;position:fixed;inset:0;background:rgba(15,23,42,.6);z-index:999;align-items:center;justify-content:center;flex-direction:column;gap:14px}
.loading-overlay.show{display:flex}
.spinner{width:40px;height:40px;border:4px solid rgba(255,255,255,.2);border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.loading-text{color:#fff;font-weight:600;font-size:13px}
.inline-error{display:none;align-items:flex-start;gap:8px;padding:10px 13px;border-radius:var(--radius-sm);margin-bottom:12px;font-size:12px;font-weight:500;background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}
.inline-error.show{display:flex}
.pill{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:50px;font-size:10px;font-weight:700}
.pill-late{background:#fef3c7;color:#78350f}
.pill-half{background:#dbeafe;color:#1e3a8a}
.pill-ontime{background:#d1fae5;color:#065f46}
.att-stat-card{background:var(--bg);border:1px solid var(--border);border-radius:9px;padding:10px;text-align:center}
.att-stat-num{font-size:20px;font-weight:800}
.att-stat-lbl{font-size:9px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-top:2px}

/* ═══ RESPONSIVE ═══ */
@media(max-width:1024px){.two-col{grid-template-columns:1fr}}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .content{margin-left:0}
  .page{padding:10px}
  .quick-grid{grid-template-columns:repeat(5,1fr);gap:6px}
  .two-col{grid-template-columns:1fr}
  .topbar-logout-btn span{display:none} /* hide text, show icon only on small mobile */
}
@media(max-width:400px){
  .quick-grid{gap:5px}
  .qc-icon{width:30px;height:30px;font-size:13px}
  .qc-title{font-size:9px}
  .topbar-logout-btn{padding:5px 8px}
}

/* Desktop sidebar always visible */
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay{display:none !important}
  .content{margin-left:var(--sidebar-w)}
}
</style>
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<div class="layout">

<!-- ═══ SIDEBAR ═══ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub">Employee</div>
    </div>
  </div>

  <div class="sidebar-user-info">
    <img src="<?= h($photo_url) ?>" alt="" class="sidebar-avatar-img">
    <div>
      <div class="sidebar-uname"><?= h($username) ?></div>
      <div class="sidebar-role">Employee</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_employee.php" class="nav-link-s active"><i class="fas fa-gauge-high"></i> Dashboard</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="apply_leave.php"        class="nav-link-s"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense_claim_add.php"            class="nav-link-s"><i class="fas fa-receipt"></i> Expenses</a></li>
    <li class="nav-item"><a href="tasks_employee.php"     class="nav-link-s"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="daily_report.php"       class="nav-link-s"><i class="fas fa-file-lines"></i> Attendance &amp; Report</a></li>
    <li class="nav-item"><a href="employee_grievance.php" class="nav-link-s"><i class="fas fa-exclamation-triangle"></i> Grievance</a></li>
  </ul>
  <div class="nav-group-label">External</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="https://pep.mypeopleconnect.app" target="_blank" class="nav-link-s"><i class="fas fa-chart-line"></i> PEP</a></li>
    <li class="nav-item"><a href="view_notifications.php" class="nav-link-s"><i class="fas fa-seedling"></i> MGT</a></li>
  </ul>

  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item">
        <a href="logout.php" class="nav-link-s danger" onclick="return confirm('Logout?')">
          <i class="fas fa-right-from-bracket"></i> Logout
        </a>
      </li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">

  <!-- TOPBAR -->
  <div class="topbar">
    <button class="hamburger-btn" id="hamburgerBtn" onclick="toggleSidebar()" aria-label="Toggle menu">
      <i class="fas fa-bars"></i>
    </button>
    <div class="topbar-title">Dashboard</div>
    <div class="topbar-right">
      <img src="<?= h($photo_url) ?>" alt="Profile" class="topbar-avatar" title="<?= h($username) ?>">
      <a href="logout.php" class="topbar-logout-btn"
         onclick="return confirm('Logout?')" title="Logout">
        <i class="fas fa-right-from-bracket"></i>
        <span>Logout</span>
      </a>
    </div>
  </div>

  <!-- PAGE -->
  <div class="page">

    <!-- Page Header -->
    <div class="page-header">
      <div class="page-title">👋 Welcome, <?= h($username) ?>!</div>
      <div class="page-subtitle">Employee Dashboard · <?= date('D, d M Y') ?></div>
    </div>

    <!-- QUICK ACCESS — 5 columns, compact -->
    <div class="quick-grid">
      <a href="#attendance-card"       class="quick-card"><div class="qc-icon rose"><i class="fas fa-fingerprint"></i></div><div class="qc-title">Check In/Out</div></a>
      <a href="#personal"              class="quick-card"><div class="qc-icon indigo"><i class="fas fa-user"></i></div><div class="qc-title">Profile</div></a>
      <a href="apply_leave.php"        class="quick-card"><div class="qc-icon cyan"><i class="fas fa-plane-departure"></i></div><div class="qc-title">Leave</div></a>
      <a href="tasks_employee.php"     class="quick-card"><div class="qc-icon emerald"><i class="fas fa-tasks"></i></div><div class="qc-title">Tasks</div></a>
      <a href="https://pep.mypeopleconnect.app" target="_blank" class="quick-card"><div class="qc-icon blue"><i class="fas fa-chart-line"></i></div><div class="qc-title">PEP</div></a>
      <a href="view_notifications.php" class="quick-card"><div class="qc-icon amber"><i class="fas fa-seedling"></i></div><div class="qc-title">MGT</div></a>
      <a href="#cab"                   class="quick-card"><div class="qc-icon pink"><i class="fas fa-credit-card"></i></div><div class="qc-title">CAB</div></a>
      <a href="employee_grievance.php" class="quick-card"><div class="qc-icon orange"><i class="fas fa-exclamation-triangle"></i></div><div class="qc-title">Grievance</div></a>
      <a href="expense_claim_add.php"            class="quick-card"><div class="qc-icon purple"><i class="fas fa-receipt"></i></div><div class="qc-title">Claims</div></a>
      <a href="#pwd"                   class="quick-card"><div class="qc-icon amber"><i class="fas fa-key"></i></div><div class="qc-title">Password</div></a>
    </div>

    <!-- ═══ MY ATTENDANCE / CHECK-IN-CHECK-OUT (NEW, full width) ═══ -->
    <div class="dash-card" id="attendance-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-fingerprint"></i> My Attendance Today</div>
        <span style="font-size:11px;color:var(--muted);font-family:'DM Mono',monospace"><?= date('D, d M Y') ?> · 9:30 AM – 6:30 PM</span>
      </div>
      <div class="dash-card-body">

        <?php if (!empty($attendance_msg)): ?>
          <div class="upload-alert <?= $attendance_type === 'success' ? 'success' : 'error' ?>" style="margin-bottom:10px">
            <i class="fas <?= $attendance_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
            <?= h($attendance_msg) ?>
          </div>
        <?php endif; ?>

        <!-- Monthly roll-up counters -->
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(90px,1fr));gap:8px;margin-bottom:14px">
          <div class="att-stat-card"><div class="att-stat-num" style="color:var(--accent)"><?= $my_checkin_count ?></div><div class="att-stat-lbl">Check-ins</div></div>
          <div class="att-stat-card"><div class="att-stat-num" style="color:var(--green)"><?= $my_checkout_count ?></div><div class="att-stat-lbl">Check-outs</div></div>
          <div class="att-stat-card"><div class="att-stat-num" style="color:var(--amber)"><?= $my_late_count ?></div><div class="att-stat-lbl">Late</div></div>
          <div class="att-stat-card"><div class="att-stat-num" style="color:#1e3a8a"><?= $my_halfday_count ?></div><div class="att-stat-lbl">Half Days</div></div>
          <!-- MONTHLY WORKING HOURS (NEW) -->
          <div class="att-stat-card"><div class="att-stat-num" style="color:var(--accent-2)"><?= $my_monthly_hours ? number_format((float)$my_monthly_hours['total_working_hours'],2) : '0.00' ?></div><div class="att-stat-lbl">Monthly Hrs</div></div>
        </div>

        <!-- MONTHLY CL (NEW) -->
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px">
          <span class="badge-custom badge-blue">Monthly CL: <?= $my_cl_status['monthly_cl'] ?></span>
          <span class="badge-custom <?= $my_cl_status['cl_used']?'badge-danger':'badge-success' ?>">CL Used: <?= $my_cl_status['cl_used'] ?></span>
          <span class="badge-custom <?= $my_cl_status['cl_available']?'badge-success':'badge-danger' ?>">CL Available: <?= $my_cl_status['cl_available'] ?></span>
        </div>

        <!-- Status track -->
        <div class="status-track">
          <div class="status-step">
            <div class="step-dot <?= $my_checked_in ? ($my_today_flags['late']?'late':'done') : 'active' ?>">
              <i class="fas <?= $my_checked_in ? 'fa-check' : 'fa-sun' ?>"></i>
            </div>
            <div class="step-label">Check-in</div>
            <?php if ($my_checked_in): ?>
              <div class="step-time"><?= date('h:i A', strtotime($my_today['login_time'])) ?></div>
              <?php if ($my_today_flags['late']): ?><span class="pill pill-late mt-1"><i class="fas fa-clock"></i> Late</span><?php else: ?><span class="pill pill-ontime mt-1"><i class="fas fa-check"></i> On Time</span><?php endif; ?>
            <?php endif; ?>
          </div>
          <div class="status-step">
            <div class="step-dot <?= $my_checked_out ? ($my_today_flags['half_day']?'late':'done') : ($my_checked_in?'active':'') ?>">
              <i class="fas <?= $my_checked_out ? 'fa-check' : 'fa-moon' ?>"></i>
            </div>
            <div class="step-label">Check-out</div>
            <?php if ($my_checked_out): ?>
              <div class="step-time"><?= date('h:i A', strtotime($my_today['logout_time'])) ?></div>
              <?php if ($my_today_flags['half_day']): ?><span class="pill pill-half mt-1"><i class="fas fa-hourglass-half"></i> Half Day</span><?php else: ?><span class="pill pill-ontime mt-1"><i class="fas fa-check"></i> Full Day</span><?php endif; ?>
              <?php if (!empty($my_today['daily_working_hours'])): ?><div class="step-time" style="margin-top:3px"><?= number_format((float)$my_today['daily_working_hours'],2) ?> hrs</div><?php endif; ?>
            <?php endif; ?>
          </div>
        </div>

        <?php if (!$my_checked_in): ?>
          <!-- CHECK-IN CAPTURE -->
          <div class="inline-error" id="ciError"><i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i><span id="ciErrorMsg"></span></div>
          <div class="camera-error-box" id="ciCameraErrorBox">
            <i class="fas fa-video-slash"></i>
            <p id="ciCameraErrorMsg">Camera could not start.</p>
            <button type="button" style="background:var(--amber);color:#fff;border:none;padding:8px 16px;border-radius:8px;font-weight:600;cursor:pointer" onclick="location.reload()"><i class="fas fa-redo"></i> Tap to Retry</button>
          </div>
          <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:10px">
            <div style="flex:1;min-width:140px">
              <label style="display:block;font-size:11px;font-weight:600;color:var(--ink-2);margin-bottom:4px;text-transform:uppercase">Location Type</label>
              <select id="ci_loc_type" class="form-control" style="width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:7px;font-size:12.5px">
                <option value="Office">Office</option><option value="Client Visit">Client Visit</option>
                <option value="Field Work">Field Work</option><option value="Work From Home">Work From Home</option>
              </select>
            </div>
            <div style="flex:1;min-width:140px" id="ciCliWrap" style="display:none">
              <label style="display:block;font-size:11px;font-weight:600;color:var(--ink-2);margin-bottom:4px;text-transform:uppercase">Client Name</label>
              <input type="text" id="ci_cli_name" style="width:100%;padding:8px 10px;border:1px solid var(--border);border-radius:7px;font-size:12.5px" placeholder="Enter client name">
            </div>
          </div>
          <div class="camera-wrap" id="ciCameraWrap">
            <div class="camera-loading" id="ciCameraLoading"><i class="fas fa-circle-notch"></i><span>Starting camera…</span></div>
            <video id="empAttVideo" autoplay playsinline muted style="display:none"></video>
            <div class="camera-overlay" id="ciCameraOverlay" style="display:none"><i class="fas fa-circle" style="color:#ef4444;font-size:8px"></i> Live</div>
          </div>
          <canvas id="empAttCanvas"></canvas>
          <img id="empAttPreview" alt="Selfie preview">
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button style="padding:8px 16px;border-radius:8px;border:1px solid var(--border);background:#fff;color:var(--ink-2);font-weight:600;cursor:pointer" id="ciCapBtn" onclick="ciCapture()" disabled><i class="fas fa-camera"></i> Capture Selfie</button>
            <button style="padding:8px 16px;border-radius:8px;border:1px solid var(--border);background:#fff;color:var(--ink-2);font-weight:600;cursor:pointer;display:none" id="ciRetakeBtn" onclick="ciRetake()"><i class="fas fa-rotate-left"></i> Retake</button>
            <button class="upload-btn" id="ciSubmitBtn" style="display:none;margin-top:0" onclick="ciSubmit()"><i class="fas fa-right-to-bracket"></i> Check In</button>
          </div>

        <?php elseif (!$my_checked_out): ?>
          <!-- CHECK-OUT (camera + geolocation, both captured automatically on tap) -->
          <div class="inline-error" id="coError"><i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i><span id="coErrorMsg"></span></div>
          <div class="camera-error-box" id="coCameraErrorBox">
            <i class="fas fa-video-slash"></i>
            <p id="coCameraErrorMsg">Camera could not start.</p>
            <button type="button" style="background:var(--amber);color:#fff;border:none;padding:8px 16px;border-radius:8px;font-weight:600;cursor:pointer" onclick="location.reload()"><i class="fas fa-redo"></i> Tap to Retry</button>
          </div>
          <div class="loc-status" id="coLocStatus"><i class="fas fa-spinner fa-spin"></i><span id="coLocStatusMsg">Getting location…</span></div>
          <p style="font-size:12px;color:var(--muted);margin-bottom:10px">You're checked in since <?= date('h:i A', strtotime($my_today['login_time'])) ?>. Tap <strong>Check Out</strong> — your selfie and location are captured automatically, no extra steps.</p>
          <div class="camera-wrap" id="coCameraWrap">
            <div class="camera-loading" id="coCameraLoading"><i class="fas fa-circle-notch"></i><span>Starting camera…</span></div>
            <video id="empCoVideo" autoplay playsinline muted style="display:none"></video>
            <div class="camera-overlay" id="coCameraOverlay" style="display:none"><i class="fas fa-circle" style="color:#ef4444;font-size:8px"></i> Live</div>
          </div>
          <canvas id="empCoCanvas"></canvas>
          <img id="empCoPreview" alt="Checkout selfie preview">
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="upload-btn" id="coSubmitBtn" style="margin-top:0" disabled onclick="coSubmit()"><i class="fas fa-right-from-bracket"></i> Check Out</button>
          </div>

        <?php else: ?>
          <div style="text-align:center;padding:16px;color:var(--green)">
            <i class="fas fa-circle-check" style="font-size:1.6rem;margin-bottom:6px;display:block"></i>
            <strong style="font-size:13px">Today's attendance is complete.</strong>
            <div style="font-size:11.5px;color:var(--muted);margin-top:4px">
              In: <?= date('h:i A', strtotime($my_today['login_time'])) ?> · Out: <?= date('h:i A', strtotime($my_today['logout_time'])) ?>
              <?php if (!empty($my_today['daily_working_hours'])): ?> · <?= number_format((float)$my_today['daily_working_hours'],2) ?> hrs<?php endif; ?>
            </div>
            <?php if (!empty($my_today['photo_path']) || !empty($my_today['logout_photo_path'])): ?>
            <div style="display:flex;gap:8px;justify-content:center;margin-top:8px;flex-wrap:wrap">
              <?php if (!empty($my_today['photo_path'])): ?><a href="<?= h($my_today['photo_path']) ?>" target="_blank" style="font-size:11px;color:var(--accent);text-decoration:none"><i class="fas fa-image"></i> Check-in selfie</a><?php endif; ?>
              <?php if (!empty($my_today['logout_photo_path'])): ?><a href="<?= h($my_today['logout_photo_path']) ?>" target="_blank" style="font-size:11px;color:var(--accent);text-decoration:none"><i class="fas fa-image"></i> Check-out selfie</a><?php endif; ?>
            </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- TWO COLUMN LAYOUT -->
    <div class="two-col">

      <!-- ══ LEFT ══ -->
      <div id="personal">
        <div class="dash-card">
          <div class="dash-card-header">
            <div class="dash-card-title"><i class="fas fa-user-circle"></i> Personal Information</div>
            <span class="badge-custom badge-purple">ID: <?= h($u('id','N/A')) ?></span>
          </div>
          <div class="dash-card-body">

            <!-- Profile summary -->
            <div class="profile-header">
              <img src="<?= h($photo_url) ?>" alt="Photo" class="profile-header-avatar">
              <div style="flex:1;min-width:120px">
                <div class="profile-header-name"><?= h(trim($u('first_name').' '.$u('last_name')) ?: $username) ?></div>
                <div class="profile-header-email"><?= h($u('email','—')) ?></div>
                <?php if ($u('division')): ?>
                <div class="profile-header-meta"><i class="fas fa-building" style="color:var(--accent);font-size:9px"></i><?= h($u('division')) ?></div>
                <?php endif; ?>
                <?php if ($u('date_of_joining') && $u('date_of_joining') !== '0000-00-00'): ?>
                <div class="profile-header-meta"><i class="fas fa-calendar" style="color:var(--accent-2);font-size:9px"></i>Joined <?= date('M Y', strtotime($u('date_of_joining'))) ?></div>
                <?php endif; ?>
              </div>
            </div>

            <!-- 1. Photo Upload -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)" id="acc-photo-hdr">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#fce7f3;color:#db2777"><i class="fas fa-camera"></i></div>
                  <div><div class="acc-title">Profile Photo</div><div class="acc-subtitle">Upload or change</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body" id="acc-photo-body">
                <div class="photo-upload-wrap">
                  <?php if (!empty($photo_upload_msg)): ?>
                    <div class="upload-alert <?= $photo_upload_type === 'success' ? 'success' : 'error' ?>" style="margin-bottom:8px">
                      <i class="fas <?= $photo_upload_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
                      <?= h($photo_upload_msg) ?>
                    </div>
                  <?php endif; ?>
                  <div class="photo-area">
                    <img src="<?= h($photo_url) ?>" alt="Current" id="photoPreviewCurrent" class="profile-photo-lg">
                    <div class="photo-controls">
                      <form method="POST" enctype="multipart/form-data" id="photoUploadForm">
                        <div class="photo-drop-zone" id="dropZone">
                          <input type="file" name="profile_photo" id="photoInput" accept="image/*" onchange="previewPhoto(this)">
                          <div class="dz-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                          <div class="dz-text">Tap to upload</div>
                          <div class="dz-hint">JPG/PNG · Max 5MB</div>
                        </div>
                        <div class="photo-preview-wrap" id="photoPreviewWrap">
                          <div style="display:flex;align-items:center;gap:8px;margin-top:7px">
                            <img id="photoPreviewNew" src="#" alt="Preview" style="width:38px;height:38px;border-radius:50%;object-fit:cover;border:2px solid var(--accent)">
                            <div>
                              <div id="previewFileName" style="font-size:11px;font-weight:600;color:var(--ink-2)"></div>
                              <div id="previewFileSize" style="font-size:10px;color:var(--muted)"></div>
                            </div>
                            <button type="button" onclick="clearPhoto()" style="margin-left:auto;background:none;border:none;color:var(--muted);cursor:pointer;font-size:12px"><i class="fas fa-times"></i></button>
                          </div>
                        </div>
                        <button type="submit" class="upload-btn" id="uploadBtn" disabled><i class="fas fa-upload"></i> Upload</button>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 2. Basic Details -->
            <div class="acc-section">
              <div class="acc-header open" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#ede9fe;color:#4f46e5"><i class="fas fa-id-badge"></i></div>
                  <div><div class="acc-title">Basic Details</div><div class="acc-subtitle">Employee &amp; work info</div></div>
                </div>
                <div class="acc-chevron" style="transform:rotate(180deg);background:#c7d2fe"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body open">
                <?php
                $basic = [
                  'Employee ID'=>$u('id','—'),'Username'=>$u('username','—'),'Email'=>$u('email','—'),
                  'Gender'=>$u('gender','—'),'Designation'=>$u('designation','—'),'Division'=>$u('division','—'),
                  'Position'=>$u('position','—'),'Level'=>$u('level','—'),'Location'=>$u('location','—'),
                  'Reporting Manager'=>$u('reporting_manager','—'),'Appointment Type'=>$u('appointment_type','—'),
                ];
                foreach ($basic as $label => $val):
                ?>
                <div class="info-row">
                  <span class="info-label"><?= $label ?></span>
                  <span class="info-value <?= $label==='Employee ID'?'fw-bold':'' ?>" <?= $label==='Employee ID'?'style="color:var(--accent)"':'' ?>><?= h($val) ?></span>
                </div>
                <?php endforeach; ?>
                <div class="info-row">
                  <span class="info-label">Date of Joining</span>
                  <span class="info-value"><?php $doj=$u('date_of_joining'); echo ($doj&&$doj!=='0000-00-00') ? date('M d, Y',strtotime($doj)) : '—'; ?></span>
                </div>
                <div class="info-row">
                  <span class="info-label">Status</span>
                  <span class="info-value">
                    <?php $st=strtolower($u('status',''));
                    $scls=$st==='active'?'badge-success':($st==='resigned'?'badge-danger':'badge-warning');
                    echo '<span class="badge-custom '.$scls.'">'.h(ucfirst($u('status','—'))).'</span>'; ?>
                  </span>
                </div>
              </div>
            </div>

            <!-- 3. Contact & ID -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#dbeafe;color:#1d4ed8"><i class="fas fa-id-card"></i></div>
                  <div><div class="acc-title">Contact &amp; ID</div><div class="acc-subtitle">Mobile, address &amp; IDs</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <?php foreach(['Mobile No.'=>$u('mobileno','—'),'Blood Group'=>$u('bloodgroup','—'),'PAN Card'=>$u('pancard','—'),'Aadhar Card'=>$u('aadharcard','—'),'Emergency Contact'=>$u('emergency_contact_name','—'),'Emergency Phone'=>$u('emergency_contact_phone','—'),'Address'=>$u('address','—')] as $lbl=>$val): ?>
                <div class="info-row"><span class="info-label"><?= $lbl ?></span><span class="info-value"><?= $lbl==='Address'?nl2br(h($val)):h($val) ?></span></div>
                <?php endforeach; ?>
              </div>
            </div>

            <!-- 4. Family Details -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#d1fae5;color:#059669"><i class="fas fa-people-roof"></i></div>
                  <div><div class="acc-title">Family Details</div><div class="acc-subtitle">Marital &amp; family info</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <?php foreach(['Marital Status'=>$u('marital_status','—'),"Father's Name"=>$u('father_name','—'),"Mother's Name"=>$u('mother_name','—'),'Spouse Name'=>$u('spouse_name','—'),'No. of Children'=>$u('no_of_children','—')] as $lbl=>$val): ?>
                <div class="info-row"><span class="info-label"><?= $lbl ?></span><span class="info-value"><?= h($val) ?></span></div>
                <?php endforeach; ?>
                <div class="info-row"><span class="info-label">Anniversary</span>
                  <span class="info-value"><?php $av=$u('anniversary_date'); echo ($av&&$av!=='0000-00-00') ? date('M d, Y',strtotime($av)) : '—'; ?></span>
                </div>
              </div>
            </div>

            <!-- 5. Experience -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#fef3c7;color:#d97706"><i class="fas fa-briefcase"></i></div>
                  <div><div class="acc-title">Experience</div><div class="acc-subtitle">Education &amp; work history</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <?php foreach(['Qualification'=>$u('qualification','—'),'Previous Company'=>$u('company_name','—'),'Total Experience'=>$u('total_experience_years','—').' yrs','Previous CTC'=>$u('previous_salary','—')] as $lbl=>$val): ?>
                <div class="info-row"><span class="info-label"><?= $lbl ?></span><span class="info-value"><?= h($val) ?></span></div>
                <?php endforeach; ?>
                <div class="info-row"><span class="info-label">Prev. Experience</span><span class="info-value"><?= nl2br(h($u('previous_experience','—'))) ?></span></div>
              </div>
            </div>

            <!-- 6. Bank & Financial -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#cffafe;color:#0891b2"><i class="fas fa-university"></i></div>
                  <div><div class="acc-title">Bank Details</div><div class="acc-subtitle">Bank &amp; statutory IDs</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <?php foreach(['Bank Name'=>$u('bank_name','—'),'Account No.'=>$u('account_number','—'),'IFSC Code'=>$u('ifsc_code','—'),'UAN No.'=>$u('uan_no','—'),'ESIC No.'=>$u('esic_no','—')] as $lbl=>$val): ?>
                <div class="info-row"><span class="info-label"><?= $lbl ?></span><span class="info-value"><?= h($val) ?></span></div>
                <?php endforeach; ?>
              </div>
            </div>

            <!-- 7. Appointment Letter -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#fee2e2;color:#dc2626"><i class="fas fa-file-pdf"></i></div>
                  <div><div class="acc-title">Appointment Letter</div><div class="acc-subtitle">View or download</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <div style="padding:12px 14px">
                  <?php
                  $offer_rel = 'uploads/user_' . $employee_id . '/appointment_letter.pdf';
                  $offer_abs = $document_root . '/' . $offer_rel;
                  $offer_url_path = '/' . $offer_rel;
                  if (file_exists($offer_abs) && is_readable($offer_abs)):
                  ?>
                    <div style="display:flex;justify-content:space-between;align-items:center;gap:8px">
                      <span style="font-size:12.5px;color:var(--ink-2)">Appointment Letter</span>
                      <div style="display:flex;gap:6px">
                        <a href="<?= h($offer_url_path) ?>" target="_blank" style="display:inline-flex;align-items:center;gap:4px;padding:5px 10px;background:#dbeafe;color:#1d4ed8;border-radius:7px;font-size:11.5px;font-weight:600;text-decoration:none"><i class="fas fa-eye"></i> View</a>
                        <a href="<?= h($offer_url_path) ?>" download style="display:inline-flex;align-items:center;gap:4px;padding:5px 10px;background:#d1fae5;color:#065f46;border-radius:7px;font-size:11.5px;font-weight:600;text-decoration:none"><i class="fas fa-download"></i> Save</a>
                      </div>
                    </div>
                  <?php else: ?>
                    <div class="empty-state" style="padding:14px"><i class="fas fa-file-pdf"></i><p>Not available yet.</p></div>
                  <?php endif; ?>
                </div>
              </div>
            </div>

            <!-- 8. Handbook -->
            <div class="acc-section">
              <div class="acc-header" onclick="toggleAcc(this)">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#f0fdf4;color:#059669"><i class="fas fa-book-open"></i></div>
                  <div><div class="acc-title">Employee Handbook</div><div class="acc-subtitle"><?= $total_docs ?> document<?= $total_docs !== 1 ? 's' : '' ?></div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body">
                <div style="padding:0 14px">
                  <?php if ($total_docs === 0): ?>
                    <div class="empty-state"><i class="fas fa-file-alt"></i><p>No documents available.</p></div>
                  <?php else: ?>
                    <?php foreach ($all_docs as $index => $row):
                      $status = $row['status'] ?? 'Not Acknowledged';
                      $bCls   = ($status === 'Acknowledged') ? 'badge-success' : 'badge-warning';
                    ?>
                    <div class="doc-item <?= $index >= 2 ? 'doc-extra' : '' ?>" <?= $index >= 2 ? 'style="display:none"' : '' ?>>
                      <span style="font-size:12px;color:var(--ink-2)"><?= h($row['title']) ?></span>
                      <div style="display:flex;gap:5px;align-items:center">
                        <span class="badge-custom <?= $bCls ?>"><?= h($status) ?></span>
                        <a href="view_document.php?id=<?= $row['id'] ?>" style="display:inline-flex;align-items:center;padding:4px 9px;background:#dbeafe;color:#1d4ed8;border-radius:6px;font-size:11px;font-weight:600;text-decoration:none">View</a>
                      </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if ($total_docs > 2): ?>
                      <button type="button" id="toggle-docs-btn" style="font-size:11.5px;color:var(--accent);background:none;border:none;cursor:pointer;padding:8px 0">
                        <i class="fas fa-chevron-down"></i> Show More (<?= $total_docs - 2 ?> more)
                      </button>
                    <?php endif; ?>
                  <?php endif; ?>
                </div>
              </div>
            </div>

            <!-- 9. Change Password -->
            <div class="acc-section" id="pwd">
              <div class="acc-header" onclick="toggleAcc(this)" id="acc-pwd-hdr">
                <div class="acc-header-left">
                  <div class="acc-icon" style="background:#fef9c3;color:#a16207"><i class="fas fa-lock"></i></div>
                  <div><div class="acc-title">Change Password</div><div class="acc-subtitle">Update account password</div></div>
                </div>
                <div class="acc-chevron"><i class="fas fa-chevron-down"></i></div>
              </div>
              <div class="acc-body" id="acc-pwd-body">
                <div style="padding:14px">
                  <?php if (!empty($pwd_change_msg)): ?>
                    <div class="upload-alert <?= $pwd_change_type === 'success' ? 'success' : 'error' ?>" style="margin-bottom:10px">
                      <i class="fas <?= $pwd_change_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
                      <?= h($pwd_change_msg) ?>
                    </div>
                  <?php endif; ?>
                  <form method="POST" autocomplete="off">
                    <div style="margin-bottom:10px">
                      <label class="pwd-field-label">Current Password <span>*</span></label>
                      <div class="pwd-input-wrap">
                        <input type="password" name="current_password" id="currentPwdInput" required placeholder="Current password">
                        <button type="button" class="pwd-toggle-btn" onclick="togglePwd('currentPwdInput',this)"><i class="fas fa-eye"></i></button>
                      </div>
                    </div>
                    <div style="margin-bottom:10px">
                      <label class="pwd-field-label">New Password <span>*</span></label>
                      <div class="pwd-input-wrap">
                        <input type="password" name="new_password" id="newPwdInput" required minlength="8" placeholder="Min 8 characters" oninput="checkPwdStrength(this.value)">
                        <button type="button" class="pwd-toggle-btn" onclick="togglePwd('newPwdInput',this)"><i class="fas fa-eye"></i></button>
                      </div>
                      <div style="margin-top:5px;height:3px;border-radius:3px;background:#e2e8f0;overflow:hidden">
                        <div id="pwdStrengthBar" style="height:100%;width:0;border-radius:3px;transition:width .3s,background .3s"></div>
                      </div>
                      <div id="pwdStrengthLabel" style="font-size:9.5px;color:var(--muted);margin-top:2px;min-height:13px"></div>
                    </div>
                    <div style="margin-bottom:14px">
                      <label class="pwd-field-label">Confirm New Password <span>*</span></label>
                      <div class="pwd-input-wrap">
                        <input type="password" name="confirm_password" id="confirmPwdInput" required placeholder="Re-enter new password" oninput="checkPwdMatch()">
                        <button type="button" class="pwd-toggle-btn" onclick="togglePwd('confirmPwdInput',this)"><i class="fas fa-eye"></i></button>
                      </div>
                      <div id="pwdMatchMsg" style="font-size:10.5px;margin-top:2px;min-height:13px"></div>
                    </div>
                    <button type="submit" class="upload-btn" style="width:100%;justify-content:center;padding:10px">
                      <i class="fas fa-key"></i> Update Password
                    </button>
                  </form>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
      <!-- END LEFT -->

      <!-- ══ RIGHT ══ -->
      <div id="cab">

        <!-- Payslips -->
        <div class="dash-card">
          <div class="dash-card-header">
            <div class="dash-card-title"><i class="fas fa-file-invoice-dollar"></i> Payslips</div>
            <span class="badge-custom badge-blue"><?= $payslip_count ?> records</span>
          </div>
          <div class="dash-card-body p0">
            <?php if ($result_payslips && $payslip_count > 0): ?>
              <div class="tbl-wrap tbl-wrap-scroll">
                <table class="dash-table">
                  <thead><tr><th>Month</th><th>Net Pay</th><th>Status</th><th></th></tr></thead>
                  <tbody>
                  <?php while ($p = $result_payslips->fetch_assoc()):
                    $rawMonth   = $p['month'];
                    $netPay     = (float)($p['grand_total'] ?? 0);
                    $statusRaw  = strtolower(trim($p['status'] ?? ''));
                    $monthLabel = preg_match('/^\d{4}-\d{2}$/', $rawMonth) ? date('M Y', strtotime($rawMonth . '-01')) : h($rawMonth);
                    $statusClean = $payroll_has_status ? ($statusRaw ?: 'draft') : 'released';
                    $canView     = !$payroll_has_status || in_array($statusClean, ['sent','approved','released','paid']);
                    $bCls = in_array($statusClean, ['approved','released','paid']) ? 'badge-success' : (in_array($statusClean, ['rejected','cancelled']) ? 'badge-danger' : 'badge-warning');
                  ?>
                  <tr>
                    <td><strong><?= $monthLabel ?></strong></td>
                    <td style="font-family:'DM Mono',monospace;font-size:11.5px">₹<?= number_format($netPay, 2) ?></td>
                    <td><span class="badge-custom <?= $bCls ?>"><?= ucfirst($statusClean) ?></span></td>
                    <td>
                      <?php if ($canView): ?>
                        <a href="payslip.php?id=<?= urlencode($p['id']) ?>" target="_blank" style="display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;background:#dbeafe;color:#1d4ed8;border-radius:6px;text-decoration:none;font-size:11px">
                          <i class="fas fa-eye"></i>
                        </a>
                      <?php else: ?><small style="color:var(--muted)">–</small><?php endif; ?>
                    </td>
                  </tr>
                  <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            <?php else: ?>
              <div class="empty-state"><i class="fas fa-file-invoice-dollar"></i><p>No payslips yet.</p></div>
            <?php endif; ?>
          </div>
        </div>

        <!-- Leave Balance (always shows CL / SL / Comp Off, defaulting to 0) -->
        <div class="dash-card">
          <div class="dash-card-header">
            <div class="dash-card-title"><i class="fas fa-umbrella-beach"></i> Leave Balance</div>
            <a href="apply_leave.php" style="display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600;border:1.5px solid #0891b2;color:#0891b2;text-decoration:none;transition:.15s" onmouseover="this.style.background='#0891b2';this.style.color='#fff'" onmouseout="this.style.background='transparent';this.style.color='#0891b2'"><i class="fas fa-plus"></i> Apply</a>
          </div>
          <div class="dash-card-body">
            <div class="leave-grid">
              <?php foreach ($leave_balance_rows as $lb):
                $colors = ['CL'=>['bg'=>'#ede9fe','txt'=>'#4f46e5'],'SL'=>['bg'=>'#cffafe','txt'=>'#0891b2'],'Compensatory'=>['bg'=>'#fce7f3','txt'=>'#db2777'],'default'=>['bg'=>'#f1f5f9','txt'=>'#334155']];
                $clr = $colors[$lb['leave_type']] ?? $colors['default'];
                $label = $lb['leave_type'] === 'Compensatory' ? 'Comp Off' : $lb['leave_type'];
              ?>
                <div class="leave-card" style="background:<?= $clr['bg'] ?>">
                  <div class="leave-card-type" style="color:<?= $clr['txt'] ?>"><?= h($label) ?></div>
                  <div class="leave-card-num" style="color:<?= $clr['txt'] ?>"><?= (int)$lb['balance'] ?></div>
                  <div class="leave-card-label" style="color:<?= $clr['txt'] ?>">days</div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>

        <!-- Upcoming Holidays -->
        <div class="dash-card">
          <div class="dash-card-header">
            <div class="dash-card-title"><i class="fas fa-calendar-check"></i> Upcoming Holidays</div>
            <?php if (count($holiday_rows) > 0): ?><span class="badge-custom badge-cyan"><?= count($holiday_rows) ?> upcoming</span><?php endif; ?>
          </div>
          <div class="dash-card-body p0">
            <?php if (!empty($holiday_rows)): ?>
              <table class="dash-table">
                <thead><tr><th>Date</th><th>Holiday</th><th>Type</th></tr></thead>
                <tbody>
                <?php foreach ($holiday_rows as $i => $hrow): ?>
                  <tr class="<?= $i >= 3 ? 'extra-holiday' : '' ?>" <?= $i >= 3 ? 'style="display:none"' : '' ?>>
                    <td style="white-space:nowrap;font-size:10.5px;font-family:'DM Mono',monospace"><?= date('d M Y', strtotime($hrow['holiday_date'])) ?></td>
                    <td>
                      <div style="font-size:11.5px;font-weight:600"><?= htmlspecialchars($hrow['name']) ?></div>
                      <?php if (!empty($hrow['location'])): ?>
                        <div style="font-size:10px;color:var(--muted);margin-top:1px">📍 <?= htmlspecialchars($hrow['location']) ?></div>
                      <?php endif; ?>
                    </td>
                    <td><?= !empty($hrow['is_optional']) ? '<span class="badge-custom badge-warning">Optional</span>' : '<span class="badge-custom badge-success">Mandatory</span>' ?></td>
                  </tr>
                <?php endforeach; ?>
                </tbody>
              </table>
              <?php if (count($holiday_rows) > 3): ?>
                <div style="padding:8px 12px;border-top:1px solid var(--border)">
                  <button id="toggle-holiday" style="font-size:11.5px;color:var(--accent);background:none;border:none;cursor:pointer">
                    <i class="fas fa-chevron-down"></i> Show more (<?= count($holiday_rows) - 3 ?>)
                  </button>
                </div>
              <?php endif; ?>
            <?php else: ?>
              <div class="empty-state"><i class="fas fa-calendar"></i><p>No upcoming holidays.</p></div>
            <?php endif; ?>
          </div>
        </div>

      </div>
      <!-- END RIGHT -->
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<div class="loading-overlay" id="loadingOverlay">
  <div class="spinner"></div>
  <div class="loading-text" id="loadingText">Processing…</div>
</div>

<script>
/* ── SIDEBAR — fixed for both mobile and desktop ── */
var sidebar  = document.getElementById('sidebar');
var overlay  = document.getElementById('sidebarOverlay');

function isMobile(){ return window.innerWidth < 769; }

function openSidebar(){
  sidebar.classList.add('open');
  if(isMobile()){ overlay.classList.add('active'); document.body.style.overflow='hidden'; }
}
function closeSidebar(){
  sidebar.classList.remove('open');
  overlay.classList.remove('active');
  document.body.style.overflow='';
}
function toggleSidebar(){
  sidebar.classList.contains('open') ? closeSidebar() : openSidebar();
}

window.addEventListener('resize', function(){
  if(!isMobile()){
    overlay.classList.remove('active');
    document.body.style.overflow='';
  }
});

document.addEventListener('keydown', function(e){ if(e.key==='Escape') closeSidebar(); });

/* ── ACCORDION ── */
function toggleAcc(header){
  var body    = header.nextElementSibling;
  var chevron = header.querySelector('.acc-chevron');
  var isOpen  = header.classList.contains('open');
  if(isOpen){
    header.classList.remove('open');
    chevron.style.transform='';
    chevron.style.background='';
    body.classList.remove('open');
    body.style.display='none';
  } else {
    header.classList.add('open');
    chevron.style.transform='rotate(180deg)';
    chevron.style.background='#c7d2fe';
    body.classList.add('open');
    body.style.display='block';
  }
}

/* ── PHOTO UPLOAD ── */
function previewPhoto(input){
  var file=input.files[0]; if(!file) return;
  var reader=new FileReader();
  reader.onload=function(e){
    document.getElementById('photoPreviewNew').src=e.target.result;
    document.getElementById('previewFileName').textContent=file.name;
    document.getElementById('previewFileSize').textContent=(file.size/1024).toFixed(1)+' KB';
    document.getElementById('photoPreviewWrap').style.display='block';
    document.getElementById('uploadBtn').disabled=false;
  };
  reader.readAsDataURL(file);
}
function clearPhoto(){
  document.getElementById('photoInput').value='';
  document.getElementById('photoPreviewWrap').style.display='none';
  document.getElementById('uploadBtn').disabled=true;
}
var dropZone=document.getElementById('dropZone');
if(dropZone){
  ['dragenter','dragover'].forEach(function(ev){ dropZone.addEventListener(ev,function(e){ e.preventDefault(); dropZone.classList.add('drag-over'); }); });
  ['dragleave','drop'].forEach(function(ev){ dropZone.addEventListener(ev,function(e){ e.preventDefault(); dropZone.classList.remove('drag-over'); }); });
  dropZone.addEventListener('drop',function(e){
    var file=e.dataTransfer.files[0];
    if(file&&file.type.startsWith('image/')){
      var dt=new DataTransfer(); dt.items.add(file);
      document.getElementById('photoInput').files=dt.files;
      previewPhoto(document.getElementById('photoInput'));
    }
  });
}
<?php if (!empty($photo_upload_msg)): ?>
(function(){ var hdr=document.getElementById('acc-photo-hdr'); if(hdr&&!hdr.classList.contains('open')) toggleAcc(hdr); })();
<?php endif; ?>

/* ── DOCS TOGGLE ── */
var toggleDocsBtn=document.getElementById('toggle-docs-btn');
if(toggleDocsBtn){
  toggleDocsBtn.addEventListener('click',function(){
    var extras=document.querySelectorAll('.doc-extra');
    var showing=extras[0]&&extras[0].style.display!=='none';
    extras.forEach(function(el){ el.style.display=showing?'none':''; });
    var more=<?= max(0, $total_docs - 2) ?>;
    this.innerHTML=showing?'<i class="fas fa-chevron-down"></i> Show More ('+more+' more)':'<i class="fas fa-chevron-up"></i> Show Fewer';
  });
}

/* ── HOLIDAY TOGGLE ── */
var toggleHoliday=document.getElementById('toggle-holiday');
if(toggleHoliday){
  toggleHoliday.addEventListener('click',function(){
    var rows=document.querySelectorAll('.extra-holiday');
    var showing=rows[0]&&rows[0].style.display!=='none';
    rows.forEach(function(r){ r.style.display=showing?'none':''; });
    this.innerHTML=showing?'<i class="fas fa-chevron-down"></i> Show more ('+rows.length+')':'<i class="fas fa-chevron-up"></i> Show less';
  });
}

/* ── PASSWORD ── */
function togglePwd(inputId,btn){
  var input=document.getElementById(inputId);
  var icon=btn.querySelector('i');
  if(input.type==='password'){ input.type='text'; icon.classList.replace('fa-eye','fa-eye-slash'); }
  else{ input.type='password'; icon.classList.replace('fa-eye-slash','fa-eye'); }
}
function checkPwdStrength(val){
  var bar=document.getElementById('pwdStrengthBar');
  var label=document.getElementById('pwdStrengthLabel');
  var score=0;
  if(val.length>=8) score++; if(val.length>=12) score++;
  if(/[A-Z]/.test(val)) score++; if(/[0-9]/.test(val)) score++;
  if(/[^A-Za-z0-9]/.test(val)) score++;
  var levels=[{pct:'0%',bg:'',txt:''},{pct:'25%',bg:'#ef4444',txt:'Weak'},{pct:'50%',bg:'#f97316',txt:'Fair'},{pct:'75%',bg:'#eab308',txt:'Good'},{pct:'100%',bg:'#22c55e',txt:'Strong'}];
  var lvl=levels[Math.min(score,4)];
  bar.style.width=lvl.pct; bar.style.background=lvl.bg;
  label.textContent=lvl.txt; label.style.color=lvl.bg||'var(--muted)';
}
function checkPwdMatch(){
  var np=document.getElementById('newPwdInput').value;
  var cp=document.getElementById('confirmPwdInput').value;
  var msg=document.getElementById('pwdMatchMsg');
  if(!cp){ msg.textContent=''; return; }
  msg.textContent=np===cp?'✓ Passwords match':'✗ Passwords do not match';
  msg.style.color=np===cp?'#059669':'#dc2626';
}
<?php if (!empty($pwd_change_msg)): ?>
(function(){ var hdr=document.getElementById('acc-pwd-hdr'); if(hdr&&!hdr.classList.contains('open')) toggleAcc(hdr); })();
<?php endif; ?>

/* ══════════════════════════════════════════════
   CHECK-IN CAMERA + LOCATION (same approach as manager dashboard)
══════════════════════════════════════════════ */
var ciVideo=document.getElementById('empAttVideo');
var ciCanvas=document.getElementById('empAttCanvas');
var ciPreview=document.getElementById('empAttPreview');
var ciCapBtn=document.getElementById('ciCapBtn');
var ciRetakeBtn=document.getElementById('ciRetakeBtn');
var ciSubmitBtn=document.getElementById('ciSubmitBtn');
var ciCameraWrap=document.getElementById('ciCameraWrap');
var ciCameraLoading=document.getElementById('ciCameraLoading');
var ciCameraOverlay=document.getElementById('ciCameraOverlay');
var ciCameraErrBox=document.getElementById('ciCameraErrorBox');
var ciCameraErrMsg=document.getElementById('ciCameraErrorMsg');
var ciPhotoData='';
var ciCameraReady=false;

function ciShowErr(msg){ var el=document.getElementById('ciError'),ml=document.getElementById('ciErrorMsg'); if(!el||!ml) return; ml.textContent=msg; el.classList.add('show'); setTimeout(()=>el.classList.remove('show'),6000); }

function ciShowCameraError(msg){
  if(ciCameraLoading) ciCameraLoading.style.display='none';
  if(ciVideo) ciVideo.style.display='none';
  if(ciCameraOverlay) ciCameraOverlay.style.display='none';
  if(ciCameraWrap) ciCameraWrap.style.minHeight='0';
  if(ciCameraErrMsg) ciCameraErrMsg.textContent = msg || 'Camera could not start. Tap to retry.';
  if(ciCameraErrBox) ciCameraErrBox.classList.add('show');
  if(ciCapBtn){ ciCapBtn.disabled=true; ciCapBtn.style.display='none'; }
}

if (ciVideo) {
  if(!navigator.mediaDevices) navigator.mediaDevices = {};
  if(!navigator.mediaDevices.getUserMedia){
    var legacy = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || null;
    if(legacy){
      navigator.mediaDevices.getUserMedia = function(c){ return new Promise(function(res,rej){ legacy.call(navigator,c,res,rej); }); };
    }
  }
  (async function startCiCam(){
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){ ciShowCameraError('Camera not supported in this browser. Please open in Chrome.'); return; }
    var sets=[{video:{facingMode:{ideal:'user'}},audio:false},{video:{facingMode:'user'},audio:false},{video:true,audio:false}];
    var lastErr=null;
    for(var i=0;i<sets.length;i++){
      try{
        var stream = await navigator.mediaDevices.getUserMedia(sets[i]);
        ciVideo.srcObject = stream;
        try{ await ciVideo.play(); }catch(e){}
        ciCameraReady=true;
        if(ciCameraLoading) ciCameraLoading.style.display='none';
        ciVideo.style.display='block';
        if(ciCameraOverlay) ciCameraOverlay.style.display='block';
        if(ciCapBtn) ciCapBtn.disabled=false;
        lastErr=null; break;
      }catch(err){
        lastErr=err;
        if(err.name==='NotAllowedError'||err.name==='PermissionDeniedError') break;
        if(err.name==='NotFoundError'||err.name==='DevicesNotFoundError') break;
        if(err.name==='SecurityError') break;
      }
    }
    if(!ciCameraReady && lastErr){
      var n=lastErr.name||'';
      if(n==='NotAllowedError'||n==='PermissionDeniedError') ciShowCameraError('Camera permission denied. Please allow camera access, then reopen this page.');
      else if(n==='NotFoundError'||n==='DevicesNotFoundError') ciShowCameraError('No camera found on this device.');
      else if(n==='NotReadableError'||n==='TrackStartError'||n==='AbortError') ciShowCameraError('Camera is busy. Close other apps using the camera, then tap Retry.');
      else if(n==='SecurityError') ciShowCameraError('Camera blocked by security policy. Ensure the page is using HTTPS.');
      else ciShowCameraError('Camera error: '+(lastErr.message||n)+'. Tap Retry.');
    }
  })();
}

var ciLocSelect=document.getElementById('ci_loc_type');
if (ciLocSelect) ciLocSelect.addEventListener('change', function(){
  document.getElementById('ciCliWrap').style.display = this.value==='Client Visit' ? '' : 'none';
});

function ciCapture(){
  if(!ciCameraReady || !ciVideo){ ciShowErr('Camera not ready. Please tap Retry.'); return; }
  if(!ciVideo.videoWidth || !ciVideo.videoHeight){ ciShowErr('Camera feed not active yet. Wait a moment.'); return; }
  ciCanvas.width=ciVideo.videoWidth; ciCanvas.height=ciVideo.videoHeight;
  ciCanvas.getContext('2d').drawImage(ciVideo,0,0);
  ciPhotoData=ciCanvas.toDataURL('image/jpeg',.85);
  ciPreview.src=ciPhotoData; ciPreview.style.display='block'; ciVideo.style.display='none';
  if(ciCameraOverlay) ciCameraOverlay.style.display='none';
  ciCapBtn.style.display='none'; ciRetakeBtn.style.display=''; ciSubmitBtn.style.display='';
}
function ciRetake(){
  ciPhotoData=''; ciPreview.style.display='none'; ciVideo.style.display='block';
  if(ciCameraOverlay) ciCameraOverlay.style.display='block';
  ciCapBtn.style.display=''; ciRetakeBtn.style.display='none'; ciSubmitBtn.style.display='none';
}

function getLoc(){
  return new Promise((res,rej)=>{
    if(!navigator.geolocation) return rej('Not supported');
    navigator.geolocation.getCurrentPosition(
      p=>res({lat:p.coords.latitude,lng:p.coords.longitude}),
      e=>rej(e.message||'Denied'),
      {enableHighAccuracy:true,timeout:20000,maximumAge:0}
    );
  });
}

async function ciSubmit(){
  if(!ciPhotoData){ ciShowErr('Capture selfie first.'); return; }
  var locType = document.getElementById('ci_loc_type')?.value || 'Office';
  var cliName = document.getElementById('ci_cli_name')?.value || '';
  if(locType==='Client Visit' && !cliName.trim()){ ciShowErr('Enter the client name.'); return; }

  document.getElementById('loadingText').textContent='Getting location…';
  document.getElementById('loadingOverlay').classList.add('show');
  var lat='', lng='';
  try{ var loc=await getLoc(); lat=loc.lat; lng=loc.lng; }catch(e){ /* submit without coords if location fails */ }

  document.getElementById('loadingText').textContent='Checking in…';
  const f=document.createElement('form'); f.method='POST'; f.style.display='none';
  const add=(n,v)=>{const i=document.createElement('input');i.name=n;i.value=v||'';f.appendChild(i)};
  add('action','attendance_checkin'); add('lat',lat); add('lng',lng);
  add('photo_data',ciPhotoData); add('location_type',locType); add('client_name',cliName);
  document.body.appendChild(f); f.submit();
}

/* ══════════════════════════════════════════════
   CHECK-OUT — camera starts automatically like check-in; tapping
   "Check Out" grabs a selfie frame AND the geolocation in one go,
   with no separate "capture" step required from the user.
══════════════════════════════════════════════ */
var coVideo=document.getElementById('empCoVideo');
var coCanvas=document.getElementById('empCoCanvas');
var coCameraWrap=document.getElementById('coCameraWrap');
var coCameraLoading=document.getElementById('coCameraLoading');
var coCameraOverlay=document.getElementById('coCameraOverlay');
var coCameraErrBox=document.getElementById('coCameraErrorBox');
var coCameraErrMsg=document.getElementById('coCameraErrorMsg');
var coSubmitBtn=document.getElementById('coSubmitBtn');
var coCameraReady=false;

function coShowErr(msg){ var el=document.getElementById('coError'),ml=document.getElementById('coErrorMsg'); if(!el||!ml) return; ml.textContent=msg; el.classList.add('show'); setTimeout(()=>el.classList.remove('show'),6000); }

function coShowCameraError(msg){
  if(coCameraLoading) coCameraLoading.style.display='none';
  if(coVideo) coVideo.style.display='none';
  if(coCameraOverlay) coCameraOverlay.style.display='none';
  if(coCameraWrap) coCameraWrap.style.minHeight='0';
  if(coCameraErrMsg) coCameraErrMsg.textContent = msg || 'Camera could not start. Tap to retry.';
  if(coCameraErrBox) coCameraErrBox.classList.add('show');
  if(coSubmitBtn) coSubmitBtn.disabled=true;
}

if (coVideo) {
  (async function startCoCam(){
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){ coShowCameraError('Camera not supported in this browser. Please open in Chrome.'); return; }
    var sets=[{video:{facingMode:{ideal:'user'}},audio:false},{video:{facingMode:'user'},audio:false},{video:true,audio:false}];
    var lastErr=null;
    for(var i=0;i<sets.length;i++){
      try{
        var stream = await navigator.mediaDevices.getUserMedia(sets[i]);
        coVideo.srcObject = stream;
        try{ await coVideo.play(); }catch(e){}
        coCameraReady=true;
        if(coCameraLoading) coCameraLoading.style.display='none';
        coVideo.style.display='block';
        if(coCameraOverlay) coCameraOverlay.style.display='block';
        if(coSubmitBtn) coSubmitBtn.disabled=false;
        lastErr=null; break;
      }catch(err){
        lastErr=err;
        if(err.name==='NotAllowedError'||err.name==='PermissionDeniedError') break;
        if(err.name==='NotFoundError'||err.name==='DevicesNotFoundError') break;
        if(err.name==='SecurityError') break;
      }
    }
    if(!coCameraReady && lastErr){
      var n=lastErr.name||'';
      if(n==='NotAllowedError'||n==='PermissionDeniedError') coShowCameraError('Camera permission denied. Please allow camera access, then reopen this page.');
      else if(n==='NotFoundError'||n==='DevicesNotFoundError') coShowCameraError('No camera found on this device.');
      else if(n==='NotReadableError'||n==='TrackStartError'||n==='AbortError') coShowCameraError('Camera is busy. Close other apps using the camera, then tap Retry.');
      else if(n==='SecurityError') coShowCameraError('Camera blocked by security policy. Ensure the page is using HTTPS.');
      else coShowCameraError('Camera error: '+(lastErr.message||n)+'. Tap Retry.');
    }
  })();
}

async function coSubmit(){
  if(!coCameraReady || !coVideo || !coVideo.videoWidth){ coShowErr('Camera not ready yet. Please wait a moment and try again.'); return; }

  // 1) Auto-capture the selfie frame right now
  coCanvas.width=coVideo.videoWidth; coCanvas.height=coVideo.videoHeight;
  coCanvas.getContext('2d').drawImage(coVideo,0,0);
  var coPhotoData=coCanvas.toDataURL('image/jpeg',.85);

  if(coSubmitBtn) coSubmitBtn.disabled=true;
  var locStatus=document.getElementById('coLocStatus');
  var locStatusMsg=document.getElementById('coLocStatusMsg');
  if(locStatus){ locStatus.className='loc-status getting'; locStatusMsg.textContent='Getting your location…'; }
  document.getElementById('loadingText').textContent='Getting location…';
  document.getElementById('loadingOverlay').classList.add('show');

  // 2) Auto-capture geolocation
  var lat='', lng='';
  try{
    var loc=await getLoc();
    lat=loc.lat; lng=loc.lng;
    if(locStatus){ locStatus.className='loc-status got'; locStatusMsg.textContent='Location captured successfully.'; }
  }catch(e){
    if(locStatus){ locStatus.className='loc-status failed'; locStatusMsg.textContent='Could not get location — checking out without it.'; }
    /* proceed without coordinates rather than blocking the check-out */
  }

  // 3) Submit both automatically — no further taps needed
  document.getElementById('loadingText').textContent='Checking out…';
  const f=document.createElement('form'); f.method='POST'; f.style.display='none';
  const add=(n,v)=>{const i=document.createElement('input');i.name=n;i.value=v||'';f.appendChild(i)};
  add('action','attendance_checkout'); add('lat',lat); add('lng',lng); add('photo_data',coPhotoData);
  document.body.appendChild(f); f.submit();
}

/* ── BACK BUTTON GUARD ── */
history.replaceState({p:'dashboard'},'',location.href);
history.pushState({p:'dashboard'},'',location.href);
window.addEventListener('popstate',function(){ history.pushState({p:'dashboard'},'',location.href); });
</script>
</body>
</html>
<?php $conn->close(); ?>