<?php
session_start();
include 'config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
function normalize_key($name) {
    $name = (string)$name; $name = trim($name);
    $name = preg_replace('/\s+/', ' ', $name);
    return mb_strtolower($name, 'UTF-8');
}

if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit(); }

$employee_id  = $_SESSION['user_id'];
$username     = trim($_SESSION['username'] ?? '');
$manager_name = $username; // temporary fallback until we load the real profile below

$valid_locations = ['chennai','coimbatore','madurai','bengaluru'];
$valid_levels    = ['L1','L2','L3','L4','L5'];
$base_url        = 'https://spica.mybelief.in/uploads';

/*
 * ── OFFICE TIMING RULES ──
 * 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"
 * These are used both for the manager's own attendance card and the
 * team attendance table below.
 */
$office_start_time      = '09:30:00';
$office_end_time        = '18:30:00';
$half_day_cutoff_time   = '13:00:00';

$month      = $_GET['month'] ?? date('Y-m');
$monthStart = $month . '-01';
$monthEnd   = date('Y-m-t', strtotime($monthStart));
$detail_user = isset($_GET['detail_user']) ? (int)$_GET['detail_user'] : null;
$view_report = isset($_GET['view_report']) ? (int)$_GET['view_report'] : null;
$att_date    = $_GET['att_date'] ?? date('Y-m-d'); // date shown in the Team Attendance table (defaults to today)
$today       = date('Y-m-d');

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}"); }

/*
 * ── MANAGER MATCHING (BUGFIX) ──
 * Employees have `reporting_manager` stored inconsistently — sometimes
 * the manager's USERNAME, sometimes their FULL NAME. Every widget below
 * (team list, leave balances, pending approvals, attendance, daily
 * reports, org chart) must match against BOTH values, or real team
 * members silently go missing whenever reporting_manager holds a full
 * name instead of a username (or vice-versa). mgrMatchSQL() +
 * safeMatchValue() give one reusable, correct condition used
 * everywhere in this file.
 */
function mgrMatchSQL($alias = '') {
    $col = $alias !== '' ? "{$alias}.reporting_manager" : "reporting_manager";
    return "(LOWER(TRIM({$col})) = LOWER(TRIM(?)) OR LOWER(TRIM({$col})) = LOWER(TRIM(?)))";
}
function safeMatchValue($val) {
    $val = trim((string)$val);
    // Never let a blank value match rows that also have a blank reporting_manager.
    return $val !== '' ? $val : "\0__no_match__\0";
}

ensureColumn($conn,'users','offer_accepted',"VARCHAR(20) DEFAULT NULL");
ensureColumn($conn,'users','offer_accepted_at',"DATETIME DEFAULT NULL");
ensureColumn($conn,'users','details_accepted',"VARCHAR(20) DEFAULT NULL");
ensureColumn($conn,'users','responsibilities_accepted',"VARCHAR(20) DEFAULT NULL");

/* DATABASE SAFETY — ensure new columns/tables exist without blindly
   duplicating them (ensureColumn / tableExists already guard against
   duplicate columns). These mirror migration.sql so the page still
   works even if the DBA hasn't run the SQL file yet. */
ensureColumn($conn,'daily_reports','daily_working_hours',"DECIMAL(5,2) NULL DEFAULT NULL");
ensureColumn($conn,'leave_requests','balance_deducted',"TINYINT(1) NOT NULL DEFAULT 0");
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");
}

/* Helper: classify a daily_reports row into Late / Half Day / On Time 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)) {
        $login_clock = date('H:i:s', strtotime($login_time));
        $is_late = $login_clock > $office_start_time;
    }
    if (!empty($logout_time)) {
        $logout_clock = date('H:i:s', strtotime($logout_time));
        $is_half_day = $logout_clock <= $half_day_cutoff_time;
    }
    return ['late' => $is_late, 'half_day' => $is_half_day];
}

/* ============================================================
   MONTHLY CL CALCULATION
   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()) {
        // The request overlaps this calendar month (checked via the
        // date-range overlap in the WHERE clause above). We don't need
        // to count *how many days* fall in-month for CL because the
        // business rule caps usage at exactly 1 CL day per month —
        // simply knowing an Approved/Pending CL touches this month is
        // enough to mark the monthly allowance as used/held.
        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; // a pending request doesn't "use" it yet, but blocks new applications
    return [
        'monthly_cl'     => 1,
        'cl_used'        => $used,
        'cl_available'   => $available,
        'has_approved'   => $approved_found,
        'has_pending'    => $pending_found,
        // true if the employee should be BLOCKED from applying for a new CL this month
        'blocked'        => ($approved_found || $pending_found),
    ];
}

/* Can this employee apply for a new CL request that touches [start_date, end_date]?
   Checks every calendar month the range spans. */
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
   Call this the moment a leave_requests row's status becomes the
   system's FINAL "Approved" state (e.g. from the Manager/HR/MD
   approval workflow in leave_dashboard_manager.php). It:
     - only deducts for leave_type = 'Compensatory'
     - only deducts once (guarded by balance_deducted flag)
     - uses a transaction so the leave_requests flag and the
       leave_balance row update together or not at all
   Returns true if a deduction happened, false otherwise (already
   deducted, not Comp Off, insufficient balance, etc).
   ============================================================ */
function deductCompOffIfApproved($conn, $leave_request_id) {
    // NOTE: FOR UPDATE requires a transaction, so we start one here.
    $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; // insufficient balance — do not deduct, leave flag untouched
    }

    $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;
}

/* ── PHOTO UPLOAD ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_photo'])) {
    $file = $_FILES['profile_photo'];
    $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
    $uploadOk = true;
    if (!in_array($file['type'],$allowed)) { $_SESSION['error_message']="Only JPG,PNG,GIF,WEBP allowed."; $uploadOk=false; }
    if ($file['size'] > 5*1024*1024) { $_SESSION['error_message']="File too large (max 5MB)."; $uploadOk=false; }
    if ($uploadOk) {
        $ext = pathinfo($file['name'],PATHINFO_EXTENSION);
        $filename = 'user_'.$employee_id.'_photo_'.time().'.'.$ext;
        $dest = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/uploads/'.$filename;
        if (move_uploaded_file($file['tmp_name'],$dest)) {
            $stmt = $conn->prepare("UPDATE users SET photo = ? WHERE id = ?");
            $stmt->bind_param("ss",$filename,$employee_id); $stmt->execute(); $stmt->close();
            $_SESSION['success_message'] = "Profile photo updated!";
        } else { $_SESSION['error_message'] = "Failed to upload photo."; }
    }
    header("Location: dashboard_manager.php"); exit();
}

/* ── FORM HANDLERS ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action']; $now = date('Y-m-d H:i:s');

    if ($action === 'accept_offer' && columnExists($conn,'users','offer_accepted')) {
        $sql = "UPDATE users SET offer_accepted='Accepted', offer_accepted_at=? WHERE id=?";
        $stmt = $conn->prepare($sql); if ($stmt) { $stmt->bind_param("ss",$now,$employee_id); $stmt->execute(); $stmt->close(); }
        $_SESSION['success_message'] = "Appointment letter accepted!";

    } elseif ($action === 'accept_details' && columnExists($conn,'users','details_accepted')) {
        $sql = "UPDATE users SET details_accepted='Accepted' WHERE id=?";
        $stmt = $conn->prepare($sql); if ($stmt) { $stmt->bind_param("s",$employee_id); $stmt->execute(); $stmt->close(); }
        $_SESSION['success_message'] = "Details accepted!";

    } elseif ($action === 'accept_responsibilities' && columnExists($conn,'users','responsibilities_accepted')) {
        $sql = "UPDATE users SET responsibilities_accepted='Accepted' WHERE id=?";
        $stmt = $conn->prepare($sql); if ($stmt) { $stmt->bind_param("s",$employee_id); $stmt->execute(); $stmt->close(); }
        $_SESSION['success_message'] = "Responsibilities accepted!";

    /* ── CHANGE PASSWORD ──
       Assumes the users table has a `password` column holding a
       password_hash()'d value. Falls back to a legacy plain-text
       comparison so existing (un-hashed) accounts can still change
       their password once, after which it is stored securely hashed. */
    } elseif ($action === 'change_password') {
        $current_password = $_POST['current_password'] ?? '';
        $new_password     = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->bind_param("s", $employee_id); $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc(); $stmt->close();
        $stored_hash = $row['password'] ?? '';

        $valid = $stored_hash !== '' && (
            password_verify($current_password, $stored_hash) ||
            hash_equals((string)$stored_hash, (string)$current_password)
        );

        if ($current_password === '' || $new_password === '' || $confirm_password === '') {
            $_SESSION['error_message'] = "Please fill in all password fields.";
        } elseif (!$valid) {
            $_SESSION['error_message'] = "Current password is incorrect.";
        } elseif (strlen($new_password) < 6) {
            $_SESSION['error_message'] = "New password must be at least 6 characters.";
        } elseif ($new_password !== $confirm_password) {
            $_SESSION['error_message'] = "New password and confirmation do not match.";
        } else {
            $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param("ss", $new_hash, $employee_id); $stmt->execute(); $stmt->close();
            $_SESSION['success_message'] = "Password changed successfully!";
        }

    /* ── ATTENDANCE CHECK-IN ──
       Captures a selfie + geolocation and writes into daily_reports,
       which has a UNIQUE(user_id, report_date) key, so this both
       creates today's row and can be called only once successfully
       per day (a second attempt for the same day just updates it). */
    } elseif ($action === 'attendance_checkin') {
        if (empty($_POST['photo_data'])) {
            $_SESSION['error_message'] = "Selfie photo is required to check in.";
        } else {
            $dir = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/uploads/attendance/';
            if (!is_dir($dir)) mkdir($dir, 0777, 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();
                $_SESSION['success_message'] = "Checked in successfully!";
            } else {
                $_SESSION['error_message'] = "Failed to save check-in photo.";
            }
        }

    /* ── ATTENDANCE CHECK-OUT ──
       On checkout we now, inside a single transaction:
         1. Fetch today's login_time.
         2. Store logout_time + geolocation as before.
         3. Compute daily_working_hours (decimal hours) on the PHP
            backend from login_time -> logout_time.
         4. Recalculate that employee's whole month from daily_reports
            and upsert it into monthly_working_hours using
            INSERT ... ON DUPLICATE KEY UPDATE so there is only ever
            one row per (user_id, year, month). */
    } elseif ($action === 'attendance_checkout') {
        $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 (need it 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 & 3. Store logout_time, geolocation, and the computed hours.
            $stmt = $conn->prepare("UPDATE daily_reports SET logout_time=?, logout_latitude=?, logout_longitude=?, daily_working_hours=? WHERE user_id=? AND report_date=?");
            $stmt->bind_param("sdddss", $now_dt, $lat, $lng, $daily_working_hours, $employee_id, $today);
            $stmt->execute(); $stmt->close();

            // MONTHLY WORKING HOURS UPDATE
            // Recalculate the whole month for this employee from daily_reports
            // (source of truth), then upsert into monthly_working_hours.
            $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 {
                        // Fallback for older rows that predate this feature and
                        // never got daily_working_hours backfilled.
                        $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) so there is exactly one
            // row per employee per month; never creates 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();
            $_SESSION['success_message'] = "Checked out successfully!";
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error_message'] = "Checkout failed: ".$e->getMessage();
        }
    }

    header("Location: dashboard_manager.php"); exit();
}

/* ── FETCH USER DATA ── */
$required_columns = ['id','username','email','role','status'];
$optional_columns = ['responsibilities','responsibilities_accepted','mobileno','department','designation','position','date_of_joining','basic_salary','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'];
$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(); }
}

/*
 * Manager's real display name + the two values every team query below
 * matches against. We use the actual name from the users table for
 * display, and match against BOTH username and full name (never just
 * one) so team members show up regardless of how reporting_manager
 * happens to be stored for them.
 */
$manager_full_name = trim(($user['first_name'] ?? '').' '.($user['last_name'] ?? ''));
$manager_name       = $manager_full_name !== '' ? $manager_full_name : $username;
$mgr_match_username = safeMatchValue($username);
$mgr_match_fullname = safeMatchValue($manager_full_name);

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

/*
 * No "blink" for missing photos: check on the SERVER whether the file
 * actually exists on disk and only ever output a valid URL, so the
 * browser never has to load a broken image first.
 */
if (!empty($user['photo']) && file_exists($document_root.'/uploads/'.$user['photo'])) {
    $photo_url = $base_url_uploads.ltrim($user['photo'],'/').'?t='.time();
} else {
    $photo_url = $default_photo_url;
}

/* ── MY OWN ATTENDANCE (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 for the manager's own attendance: 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 — read back this manager's own current-month
   summary row from monthly_working_hours for display. */
$my_monthly_hours = null;
$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 — for the manager's own dashboard card */
$my_cl_status = getMonthlyCLStatus($conn, $employee_id, (int)date('Y', strtotime($monthStart)), (int)date('n', strtotime($monthStart)));

/* ── 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 (includes Compensatory automatically) ── */
$leave_balance_rows = [];
if (tableExists($conn,'leave_balance')) {
    $sql = "SELECT leave_type, balance FROM leave_balance WHERE user_id = ? ORDER BY leave_type";
    $stmt = $conn->prepare($sql);
    if ($stmt) { $stmt->bind_param("s",$employee_id); $stmt->execute(); $res=$stmt->get_result(); while($row=$res->fetch_assoc()) $leave_balance_rows[]=$row; $stmt->close(); }
}
/* Comp Off balance surfaced separately as well, for the dedicated card */
$my_compoff_balance = null;
foreach ($leave_balance_rows as $lb) {
    if ($lb['leave_type'] === 'Compensatory') { $my_compoff_balance = (float)$lb['balance']; break; }
}

/* ── HOLIDAYS ── */
$holiday_rows = [];
if (tableExists($conn,'company_holidays')) {
    $todayH = date('Y-m-d');
    $sql = "SELECT holiday_date, name, location, is_optional FROM company_holidays WHERE holiday_date >= ? ORDER BY holiday_date ASC LIMIT 10";
    $stmt = $conn->prepare($sql);
    if ($stmt) { $stmt->bind_param("s",$todayH); $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')) {
    $sql_docs = "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";
    $stmt_docs = $conn->prepare($sql_docs);
    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(); }
}

/* ── TEAM (direct + one level of indirect reports, matched on username OR full name — BUGFIX) ── */
$sql = "SELECT id, first_name, last_name, designation, division, level, location, reporting_manager, photo, role
        FROM users
        WHERE status='active'
        AND (
            " . mgrMatchSQL() . "
            OR LOWER(TRIM(reporting_manager)) IN (
                SELECT LOWER(TRIM(CONCAT(first_name,' ',last_name)))
                FROM users
                WHERE " . mgrMatchSQL() . "
            )
        )";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $mgr_match_username, $mgr_match_fullname, $mgr_match_username, $mgr_match_fullname);
$stmt->execute();
$result = $stmt->get_result();

$employees = [];
while ($row = mysqli_fetch_assoc($result)) {
    if ((string)$row['id'] === (string)$employee_id) continue; // never list the manager as their own report
    $level_norm = strtoupper(trim($row['level']??''));
    if (!in_array($level_norm,$valid_levels,true)) $level_norm='L2';
    $row['level'] = $level_norm;
    $loc = strtolower(trim($row['location']??''));
    if ($loc===''||$loc==='pending') $loc='chennai';
    $row['location'] = $loc;
    $employees[] = $row;
}

/* Build the manager's own "card" from their real profile, not from the team query result. */
$manager_level_norm = strtoupper(trim($user['level'] ?? 'L2'));
if (!in_array($manager_level_norm,$valid_levels,true)) $manager_level_norm='L2';
$manager_loc_norm = strtolower(trim($user['location'] ?? ''));
if ($manager_loc_norm===''||$manager_loc_norm==='pending') $manager_loc_norm='chennai';

$manager_employee = [
    'id'=>$employee_id,
    'first_name'=>$user['first_name'] ?? $manager_name,
    'last_name'=>$user['last_name'] ?? '',
    'full_name'=>$manager_name,
    'designation'=>$user['designation'] ?? 'Manager',
    'division'=>$user['division'] ?? 'Operations',
    'level'=>$manager_level_norm,
    'location'=>$manager_loc_norm,
    'photo'=>$user['photo'] ?? '',
    'reporting_manager'=>$user['reporting_manager'] ?? '',
];

/* ── HIERARCHY ── */
$hierarchy = []; $manager_key = normalize_key($manager_employee['full_name']);
foreach ($employees as $emp) {
    $mgr = trim($emp['reporting_manager']??''); if ($mgr==='') $mgr=$manager_employee['full_name'];
    $mgr_key = normalize_key($mgr); if ($mgr_key==='') $mgr_key='unmapped';
    if (!isset($hierarchy[$mgr_key])) $hierarchy[$mgr_key]=[];
    $hierarchy[$mgr_key][]=$emp;
}

function buildHierarchy($hierarchy,$managerKey,$valid_locations,$base_url,$level=1,$visited=[]) {
    $managerKey=normalize_key($managerKey);
    if ($level>15||isset($visited[$managerKey])||!isset($hierarchy[$managerKey])) return '';
    $visited[$managerKey]=true; $html='';
    foreach ($hierarchy[$managerKey] as $emp) {
        $full=trim(($emp['first_name']??'').' '.($emp['last_name']??''));
        $loc=strtolower(trim($emp['location']??'')); if (!in_array($loc,$valid_locations)) $loc='chennai';
        $locd=ucfirst($loc);
        $photo=!empty($emp['photo']) ? $base_url.'/'.$emp['photo'] : $base_url.'/default.jpg';
        $lvl=strtoupper($emp['level']??'L2'); $num=intval(substr($lvl,1)); if ($num<1||$num>5) $num=2;
        $key=normalize_key($full);
        $html.="<li class='level-l{$num}' data-name='".h($full)."' data-division='".h($emp['division']??'')."' data-location='".h($locd)."'>
            <div class='emp-card'>
                <div class='emp-photo-container'>
                    <img src='".h($photo)."' class='emp-photo' onerror=\"this.onerror=null;this.src='https://via.placeholder.com/72x72?text=N'\">
                    <div class='level-badge level-badge-".strtolower($lvl)."'>".h($lvl)."</div>
                </div>
                <div class='emp-details'><strong>".h($full)."</strong><small>".h($emp['designation']??'')."</small><small>".h($emp['division']??'')."</small><small>".h($locd)."</small></div>";
        if (isset($hierarchy[$key])) {
            $html.="<span class='toggle-icon'><i class='fas fa-chevron-up'></i></span><ul class='hierarchy-level'>";
            $html.=buildHierarchy($hierarchy,$key,$valid_locations,$base_url,$level+1,$visited);
            $html.="</ul>";
        }
        $html.="</div></li>";
    }
    return $html;
}

$total_team = count($employees);
$direct = 0;
foreach ($employees as $e) {
    $emgr = trim($e['reporting_manager']??'');
    if (strcasecmp($emgr,$username)===0 || strcasecmp($emgr,$manager_name)===0) $direct++;
}
$indirect = max(0,$total_team-$direct);

/* ── TEAM LEAVE BALANCES (includes Comp Off, matched on username OR full name) ── */
$teamBalances = [];
$balSql = $conn->prepare("SELECT u.id, CONCAT(u.first_name,' ',u.last_name) AS emp_name, lb.leave_type, lb.balance FROM users u LEFT JOIN leave_balance lb ON lb.user_id=u.id WHERE " . mgrMatchSQL('u') . " ORDER BY u.first_name");
$balSql->bind_param("ss",$mgr_match_username,$mgr_match_fullname); $balSql->execute(); $resBal=$balSql->get_result();
while ($r=$resBal->fetch_assoc()) { $teamBalances[$r['id']]['name']=$r['emp_name']; $teamBalances[$r['id']][$r['leave_type']]=(int)$r['balance']; }
$balSql->close();

/* ── PENDING LEAVES (matched on username OR full name) ── */
$leave_stmt = $conn->prepare("SELECT lr.id, lr.leave_type, lr.start_date, lr.end_date, CONCAT(u.first_name,' ',u.last_name) AS emp_name, lr.manager_comment FROM leave_requests lr JOIN users u ON u.id=lr.employee_id WHERE lr.status='Pending' AND " . mgrMatchSQL('u') . " ORDER BY lr.applied_on DESC");
$leave_stmt->bind_param("ss",$mgr_match_username,$mgr_match_fullname); $leave_stmt->execute(); $leave_result=$leave_stmt->get_result();

/* ── TEAM ATTENDANCE (built on daily_reports, per the office-timing rules, matched on username OR full name) ──
 * For the date selected in $att_date (defaults to today) we show, per team
 * member: check-in time, check-out time, a "Late" badge (check-in after
 * 09:30), a "Half Day" badge (check-out at/before 13:00), plus a summary
 * count of how many of the team have checked in / checked out so far.
 */
$att_stmt = $conn->prepare(
    "SELECT u.id AS user_id, CONCAT(u.first_name,' ',u.last_name) AS emp_name,
            dr.login_time, dr.logout_time, dr.photo_path,
            dr.latitude, dr.longitude, dr.logout_latitude, dr.logout_longitude
     FROM users u
     LEFT JOIN daily_reports dr ON dr.user_id = u.id AND dr.report_date = ?
     WHERE " . mgrMatchSQL('u') . "
     ORDER BY emp_name"
);
$att_stmt->bind_param("sss",$att_date,$mgr_match_username,$mgr_match_fullname); $att_stmt->execute();
$att_result = $att_stmt->get_result();
$att_rows = $att_result->fetch_all(MYSQLI_ASSOC); $att_stmt->close();

$team_size          = count($att_rows);
$team_checked_in    = 0;
$team_checked_out   = 0;
$team_late_count    = 0;
$team_halfday_count = 0;
foreach ($att_rows as &$ar) {
    $flags = classifyAttendance($ar['login_time'], $ar['logout_time'], $office_start_time, $half_day_cutoff_time);
    $ar['is_late']     = $flags['late'];
    $ar['is_half_day'] = $flags['half_day'];
    if (!empty($ar['login_time']))  { $team_checked_in++;  if ($flags['late'])     $team_late_count++; }
    if (!empty($ar['logout_time'])) { $team_checked_out++; if ($flags['half_day']) $team_halfday_count++; }
}
unset($ar);

/* ── DETAILED ATTENDANCE (a single employee's whole month, from daily_reports) ── */
$detail_rows=[]; $detail_name='';
if ($detail_user) {
    $dstmt=$conn->prepare("SELECT report_date, login_time, logout_time, latitude, longitude, logout_latitude, logout_longitude, photo_path, daily_working_hours FROM daily_reports WHERE user_id=? AND report_date BETWEEN ? AND ? ORDER BY report_date DESC");
    $dstmt->bind_param("iss",$detail_user,$monthStart,$monthEnd); $dstmt->execute();
    $detail_rows=$dstmt->get_result()->fetch_all(MYSQLI_ASSOC); $dstmt->close();
    foreach ($detail_rows as &$dr) {
        $flags = classifyAttendance($dr['login_time'], $dr['logout_time'], $office_start_time, $half_day_cutoff_time);
        $dr['is_late'] = $flags['late']; $dr['is_half_day'] = $flags['half_day'];
        $dr['total_hours'] = (!empty($dr['login_time']) && !empty($dr['logout_time']))
            ? gmdate('H:i:s', max(0, strtotime($dr['logout_time']) - strtotime($dr['login_time'])))
            : null;
    }
    unset($dr);
    $nq=$conn->prepare("SELECT CONCAT(first_name,' ',last_name) AS name FROM users WHERE id=?");
    $nq->bind_param("i",$detail_user); $nq->execute();
    $detail_name=$nq->get_result()->fetch_assoc()['name']??''; $nq->close();

    /* MONTHLY WORKING HOURS — this employee's summary row for the modal */
    $dmwh_stmt = $conn->prepare("SELECT total_working_hours, total_working_minutes, total_working_days FROM monthly_working_hours WHERE user_id=? AND year=? AND month=?");
    $dmwh_year = (int)date('Y', strtotime($monthStart)); $dmwh_month = (int)date('n', strtotime($monthStart));
    $dmwh_stmt->bind_param("iii", $detail_user, $dmwh_year, $dmwh_month);
    $dmwh_stmt->execute();
    $detail_monthly_hours = $dmwh_stmt->get_result()->fetch_assoc();
    $dmwh_stmt->close();
}

/* ── DAILY REPORTS (matched on username OR full name) ── */
$daily_sql="SELECT dr.id, dr.report_date, dr.daily_summary, dr.report_status, dr.latitude, dr.longitude, CONCAT(u.first_name,' ',u.last_name) AS emp_name FROM daily_reports dr JOIN users u ON u.id=dr.user_id WHERE " . mgrMatchSQL('u') . " ORDER BY dr.report_date DESC LIMIT 10";
$daily_stmt=$conn->prepare($daily_sql); $daily_stmt->bind_param("ss",$mgr_match_username,$mgr_match_fullname); $daily_stmt->execute(); $daily_result=$daily_stmt->get_result();

$report_row=null;
if ($view_report) {
    $rstmt=$conn->prepare("SELECT dr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name FROM daily_reports dr JOIN users u ON u.id=dr.user_id WHERE dr.id=?");
    $rstmt->bind_param("i",$view_report); $rstmt->execute(); $report_row=$rstmt->get_result()->fetch_assoc(); $rstmt->close();
}

if (isset($_POST['dr_id'],$_POST['dr_action'])) {
    $dr_id=(int)$_POST['dr_id']; $status=$_POST['dr_action']==='approve'?'Approved':'Reviewed';
    $stmt=$conn->prepare("UPDATE daily_reports SET report_status=? WHERE id=?");
    $stmt->bind_param("si",$status,$dr_id); $stmt->execute(); $stmt->close();
    header("Location: dashboard_manager.php?month={$month}"); exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Manager 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:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%}
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:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:9px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:16px;text-align:center;font-size:13px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px 8px;border-top:1px solid rgba(255,255,255,.06)}
.sidebar-user-info{display:flex;align-items:center;gap:10px;padding:10px 14px;margin:0 8px 4px;border-radius:8px;background:rgba(255,255,255,.04)}
.sidebar-avatar-img{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,.2);flex-shrink:0}
.sidebar-uname{font-size:12px;font-weight:600;color:rgba(255,255,255,.85);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sidebar-role{font-size:10px;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{height:56px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 18px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:36px;height:36px;border-radius:8px;border:1px solid var(--border);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:15px;flex-shrink:0;transition:background .15s}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);overflow:hidden}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px;white-space:nowrap}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500;flex-shrink:0}
.topbar-avatar-img{width:30px;height:30px;border-radius:50%;object-fit:cover;border:2px solid var(--accent-2);flex-shrink:0}

/* ═══ PAGE ═══ */
.page{padding:18px;flex:1;max-width:100%}
.page-header{margin-bottom:18px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:12px;color:var(--muted);margin-top:2px}

/* ═══ QUICK ACCESS ═══ */
.quick-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;margin-bottom:18px}
.quick-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 8px;text-align:center;color:var(--ink);text-decoration:none;transition:all .2s;box-shadow:var(--shadow);display:flex;flex-direction:column;align-items:center;gap:7px}
.quick-card:hover{transform:translateY(-3px);box-shadow:var(--shadow-md);color:var(--ink);text-decoration:none}
.quick-card .qc-icon{width:40px;height:40px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:17px;margin:0 auto}
.quick-card .qc-title{font-size:11px;font-weight:600;color:var(--ink-2)}
.qc-purple .qc-icon{background:linear-gradient(135deg,#7c3aed,#a78bfa);color:#fff}
.qc-cyan   .qc-icon{background:linear-gradient(135deg,#0891b2,#22d3ee);color:#fff}
.qc-red    .qc-icon{background:linear-gradient(135deg,#dc2626,#f87171);color:#fff}
.qc-green  .qc-icon{background:linear-gradient(135deg,#059669,#34d399);color:#fff}
.qc-amber  .qc-icon{background:linear-gradient(135deg,#d97706,#fbbf24);color:#fff}
.qc-pink   .qc-icon{background:linear-gradient(135deg,#db2777,#f472b6);color:#fff}
.qc-indigo .qc-icon{background:linear-gradient(135deg,#4f46e5,#818cf8);color:#fff}
.qc-teal   .qc-icon{background:linear-gradient(135deg,#0d9488,#2dd4bf);color:#fff}
.qc-orange .qc-icon{background:linear-gradient(135deg,#ea580c,#fb923c);color:#fff}

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

/* ═══ PROFILE PHOTO ═══ */
.profile-photo-wrap{position:relative;display:inline-block;flex-shrink:0}
.profile-photo{width:100px;height:100px;border-radius:50%;object-fit:cover;border:3px solid var(--accent);box-shadow:0 4px 16px rgba(79,70,229,.2)}
.photo-edit-btn{position:absolute;bottom:2px;right:2px;width:27px;height:27px;border-radius:50%;background:var(--accent);border:2px solid #fff;display:flex;align-items:center;justify-content:center;cursor:pointer;color:#fff;font-size:11px;transition:background .15s}
.photo-edit-btn:hover{background:#4338ca}
.photo-edit-input{display:none}

/* ═══ TABLES ═══ */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.dash-table{width:100%;border-collapse:collapse;font-size:12.5px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.6px;padding:9px 12px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 12px;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}

/* ═══ LEAVE BALANCE ═══ */
.leave-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px}
.leave-bal-card{background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:13px;text-align:center}
.leave-badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:600;margin:2px}

/* ═══ ORG CHART ═══ */
.org-wrap{overflow-x:auto;padding:8px 0}
.org-chart ul{list-style:none;padding-left:0;display:flex;justify-content:center;gap:14px;flex-wrap:wrap}
.org-chart li{border-radius:12px;padding:12px;min-width:180px;text-align:center;color:white;transition:transform .2s}
.org-chart li:hover{transform:translateY(-2px)}
.level-l1{background:linear-gradient(135deg,#7c3aed,#a78bfa)}.level-l2{background:linear-gradient(135deg,#3b82f6,#60a5fa)}
.level-l3{background:linear-gradient(135deg,#059669,#34d399)}.level-l4{background:linear-gradient(135deg,#d97706,#fbbf24)}
.level-l5{background:linear-gradient(135deg,#dc2626,#f87171)}
.emp-photo{width:64px;height:64px;border-radius:50%;object-fit:cover;border:3px solid rgba(255,255,255,.7)}
.emp-photo-container{position:relative;display:inline-block}
.level-badge{position:absolute;bottom:-3px;right:-3px;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.6rem;font-weight:700;background:rgba(0,0,0,.7);color:#fff;border:1.5px solid rgba(255,255,255,.5)}
.emp-card{position:relative;display:flex;flex-direction:column;align-items:center;gap:7px}
.emp-details strong{display:block;font-size:12px}.emp-details small{display:block;font-size:10px;opacity:.85;margin-top:1px}
.toggle-icon{position:absolute;top:4px;right:4px;cursor:pointer;opacity:.75}
.toggle-icon:hover{opacity:1}.hierarchy-level{margin-top:10px}

/* ═══ DOC ITEMS ═══ */
.doc-item{display:flex;justify-content:space-between;align-items:center;padding:11px 0;border-bottom:1px solid var(--border)}
.doc-item:last-child{border-bottom:none}
.doc-info{display:flex;align-items:center;gap:9px}
.doc-icon{width:34px;height:34px;border-radius:8px;background:#fee2e2;display:flex;align-items:center;justify-content:center;color:#dc2626;font-size:13px;flex-shrink:0}

/* ═══ SALARY CARDS ═══ */
.salary-card{background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:13px}
.salary-card small{color:var(--muted);font-size:10px;font-weight:500;text-transform:uppercase;letter-spacing:.5px}
.salary-card .amount{font-size:18px;font-weight:700;font-family:'DM Mono',monospace;color:var(--green);margin-top:4px}

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

/* ═══ ALERTS ═══ */
.alert-custom{padding:11px 14px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:13px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}
.alert-info-custom{background:#dbeafe;border-left:3px solid #3b82f6;color:#1e40af}
.alert-error-custom{background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}

/* ═══ INLINE ERROR (form validation only) ═══ */
.inline-error{display:none;align-items:flex-start;gap:10px;padding:12px 16px;border-radius:var(--radius-sm);margin-bottom:14px;font-size:13px;font-weight:500;background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}
.inline-error.show{display:flex}
.inline-error.warning{background:#fef3c7;border-left-color:var(--amber);color:#78350f}

/* ═══ MISC ═══ */
.info-row{display:flex;gap:8px;padding:7px 0;border-bottom:1px solid var(--border);align-items:flex-start}
.info-row:last-child{border-bottom:none}
.info-label{min-width:140px;font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;padding-top:2px}
.info-value{font-size:13px;color:var(--ink-2);flex:1}
.divider{height:1px;background:var(--border);margin:13px 0}
.show-more-btn{background:none;border:none;color:var(--accent);font-size:12px;font-weight:600;cursor:pointer;padding:6px 0;display:flex;align-items:center;gap:4px}
.kpi-box{background:linear-gradient(135deg,rgba(79,70,229,.04),rgba(6,182,212,.04));border:1px solid rgba(79,70,229,.12);border-radius:var(--radius-sm);padding:13px;font-size:13px;color:var(--ink-2);line-height:1.7}
.resp-box{background:#f0fdf4;border-left:3px solid var(--green);border-radius:0 var(--radius-sm) var(--radius-sm) 0;padding:13px;font-size:13px;color:var(--ink-2);line-height:1.7}
.section-toggle-btn{background:none;border:1px solid var(--border);border-radius:6px;padding:5px 12px;font-size:12px;color:var(--accent);cursor:pointer;font-weight:600;transition:all .15s}
.section-toggle-btn:hover{background:rgba(79,70,229,.05)}

/* ═══ ATTENDANCE STATUS TRACK ═══ */
.status-track{display:flex;align-items:center;gap:0;margin-bottom:20px}
.status-step{flex:1;text-align:center;position:relative}
.status-step::before{content:'';position:absolute;top:16px;left:50%;right:-50%;height:2px;background:var(--border);z-index:0}
.status-step:last-child::before{display:none}
.step-dot{width:32px;height:32px;border-radius:50%;border:2px solid var(--border);background:var(--surface);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;margin:0 auto 6px;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:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.step-time{font-size:11px;color:var(--ink-2);margin-top:2px}

/* ═══ CAMERA ═══ */
.camera-wrap{border-radius:var(--radius-sm);overflow:hidden;background:#1e293b;position:relative;margin-bottom:14px;min-height:220px;display:flex;align-items:center;justify-content:center}
#attVideo,#coVideo{width:100%;max-height:280px;object-fit:cover;display:block;border-radius:var(--radius-sm)}
#attCanvas,#coCanvas{display:none}
#attPreview,#coPreview{width:100%;max-height:220px;object-fit:cover;border-radius:var(--radius-sm);display:none;margin-bottom:10px;box-shadow:var(--shadow)}
.camera-overlay{position:absolute;top:12px;right:12px;background:rgba(0,0,0,.55);color:#fff;font-size:11px;font-weight:600;padding:4px 10px;border-radius:20px;letter-spacing:.5px}
.camera-loading{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;color:rgba(255,255,255,.7);font-size:13px;font-weight:500}
.camera-loading i{font-size:26px;animation:spin .8s linear infinite}
.camera-error-box{display:none;flex-direction:column;align-items:center;justify-content:center;padding:26px 18px;background:#fff7ed;border:2px dashed #fed7aa;border-radius:var(--radius-sm);margin-bottom:14px;text-align:center;gap:8px}
.camera-error-box.show{display:flex}
.camera-error-box i{font-size:30px;color:#f97316}
.camera-error-box p{font-size:12.5px;color:#7c2d12;line-height:1.6;max-width:280px}
.loc-status{display:none;align-items:center;gap:8px;padding:10px 14px;border-radius:var(--radius-sm);margin-bottom:14px;font-size:13px;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:16px}
.loading-overlay.show{display:flex}
.spinner{width:44px;height:44px;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:14px}

/* ═══ PILLS (late / half day / on time) ═══ */
.pill{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:50px;font-size:10.5px;font-weight:700}
.pill-late{background:#fef3c7;color:#78350f}
.pill-half{background:#dbeafe;color:#1e3a8a}
.pill-ontime{background:#d1fae5;color:#065f46}
.pill-none{background:#f1f5f9;color:#64748b}

.emp-av{width:26px;height:26px;border-radius:8px;background:#ede9fe;color:var(--accent);display:inline-flex;align-items:center;justify-content:center;font-weight:700;font-size:10px;flex-shrink:0}

/* ═══ RESPONSIVE ═══ */
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .content{margin-left:0}
  .page{padding:13px}
  .quick-grid{grid-template-columns:repeat(3,1fr)}
  .org-chart ul{flex-direction:column;align-items:center}
  .leave-grid{grid-template-columns:repeat(2,1fr)}
}
@media(max-width:480px){.quick-grid{grid-template-columns:repeat(3,1fr)}}
</style>
</head>
<body>

<!-- OVERLAY -->
<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">Manager</div>
    </div>
  </div>

  <!-- User mini-profile -->
  <div class="sidebar-user-info">
    <img src="<?= h($photo_url) ?>" alt="" class="sidebar-avatar-img">
    <div>
      <div class="sidebar-uname"><?= h($manager_name) ?></div>
      <div class="sidebar-role">Manager</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_manager.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a></li>
    <li class="nav-item"><a href="myteam.php" class="nav-link"><i class="fas fa-sitemap"></i> My Team</a></li>
  </ul>

  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="manager_daily_report.php" class="nav-link"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link"><i class="fas fa-file-alt"></i> Daily Reports</a></li>
    <li class="nav-item"><a href="leave_dashboard_manager.php" class="nav-link"><i class="fas fa-umbrella-beach"></i> Team Leaves</a></li>
    <li class="nav-item"><a href="manager_hr_leave_apply.php" class="nav-link"><i class="fas fa-plane-departure"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense_claim_add.php" class="nav-link"><i class="fas fa-receipt"></i>My Claims</a></li>
    <li class="nav-item"><a href="tasks_manager.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="expense_manager_dashboard.php" class="nav-link"><i class="fas fa-receipt"></i> Team Claims</a></li>
    <li class="nav-item"><a href="apply_grievance_manager.php" class="nav-link"><i class="fas fa-exclamation-circle"></i> Grievance</a></li>
  </ul>

  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item">
        <a href="#" class="nav-link" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
          <i class="fas fa-key"></i> Change Password
        </a>
      </li>
      <li class="nav-item">
        <a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')">
          <i class="fas fa-right-from-bracket"></i> Logout
        </a>
      </li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()" aria-label="Toggle menu"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span class="current">Dashboard</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <img src="<?= h($photo_url) ?>" alt="" class="topbar-avatar-img">
      <span style="display:none" class="d-md-inline"><?= h($manager_name) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">Welcome back, <?= h(explode(' ', $manager_name)[0]) ?> 👋</div>
      <div class="page-subtitle"><?= date('l, F j, Y') ?> · Manager Dashboard</div>
    </div>

    <!-- ALERTS -->
    <?php if (isset($_SESSION['success_message'])): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle me-2"></i><?= h($_SESSION['success_message']); unset($_SESSION['success_message']); ?></div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-times-circle me-2"></i><?= h($_SESSION['error_message']); unset($_SESSION['error_message']); ?></div>
    <?php endif; ?>

    <!-- QUICK ACCESS -->
    <div class="quick-grid">
      <a href="#section-attendance" onclick="document.getElementById('section-attendance')?.scrollIntoView({behavior:'smooth'});return false" class="quick-card qc-cyan"><div class="qc-icon"><i class="fas fa-fingerprint"></i></div><div class="qc-title">Check In/Out</div></a>
      <a href="manager_hr_leave_apply.php" class="quick-card qc-purple"><div class="qc-icon"><i class="fas fa-plane-departure"></i></div><div class="qc-title">Apply Leave</div></a>
      <a href="tasks_manager.php"          class="quick-card qc-green"><div class="qc-icon"><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 qc-indigo"><div class="qc-icon"><i class="fas fa-chart-line"></i></div><div class="qc-title">PEP</div></a>
      <a href="view_notifications.php"     class="quick-card qc-teal"><div class="qc-icon"><i class="fas fa-seedling"></i></div><div class="qc-title">MGT</div></a>
      <a href="expense_claim_add.php"       class="quick-card qc-amber"><div class="qc-icon"><i class="fas fa-receipt"></i></div><div class="qc-title">Claims</div></a>
      <a href="#section-cab" onclick="document.getElementById('section-cab')?.scrollIntoView({behavior:'smooth'});return false" class="quick-card qc-orange"><div class="qc-icon"><i class="fas fa-money-check-alt"></i></div><div class="qc-title">CAB</div></a>
      <a href="apply_grievance_manager.php" class="quick-card qc-red"><div class="qc-icon"><i class="fas fa-exclamation-triangle"></i></div><div class="qc-title">Grievance</div></a>
      <a href="leave_dashboard_manager.php" class="quick-card qc-pink"><div class="qc-icon"><i class="fas fa-umbrella-beach"></i></div><div class="qc-title">Team Leaves</div></a>
    </div>

    <!-- MY PROFILE -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-user-circle"></i> My Profile</div>
        <button class="section-toggle-btn" data-bs-toggle="modal" data-bs-target="#changePasswordModal"><i class="fas fa-key me-1"></i>Change Password</button>
      </div>
      <div class="dash-card-body">
        <div style="display:flex;gap:18px;flex-wrap:wrap;align-items:flex-start">
          <div style="text-align:center;flex-shrink:0">
            <div class="profile-photo-wrap">
              <img src="<?= h($photo_url) ?>" alt="Photo" class="profile-photo" id="profilePhotoImg">
              <label class="photo-edit-btn" for="photoUploadInput" title="Change Photo"><i class="fas fa-camera"></i></label>
              <form method="POST" enctype="multipart/form-data" id="photoUploadForm">
                <input type="file" name="profile_photo" id="photoUploadInput" class="photo-edit-input" accept="image/*" onchange="document.getElementById('photoUploadForm').submit()">
              </form>
            </div>
            <div style="margin-top:6px;font-size:11px;color:var(--muted)">Tap camera to change</div>
            <div class="mt-2">
              <span class="badge-custom badge-info"><?= h($user['role']??'N/A') ?></span>
              <span class="badge-custom badge-success mt-1"><?= h($user['status']??'N/A') ?></span>
            </div>
          </div>
          <div style="flex:1;min-width:220px">
            <div class="info-row"><div class="info-label">Username</div><div class="info-value"><strong><?= h($user['username']??'N/A') ?></strong></div></div>
            <div class="info-row"><div class="info-label">Employee ID</div><div class="info-value"><?= h($user['id']??'N/A') ?></div></div>
            <div class="info-row"><div class="info-label">Email</div><div class="info-value"><?= h($user['email']??'N/A') ?></div></div>
            <?php if (!empty($user['designation'])): ?>
            <div class="info-row"><div class="info-label">Designation</div><div class="info-value"><?= h($user['designation']) ?></div></div>
            <?php endif; ?>
            <?php if (!empty($user['department'])): ?>
            <div class="info-row"><div class="info-label">Department</div><div class="info-value"><?= h($user['department']) ?></div></div>
            <?php endif; ?>
            <?php if (!empty($user['mobileno'])): ?>
            <div class="info-row"><div class="info-label">Mobile</div><div class="info-value"><?= h($user['mobileno']) ?></div></div>
            <?php endif; ?>
            <?php if (!empty($user['date_of_joining']) && $user['date_of_joining']!=='0000-00-00'): ?>
            <div class="info-row"><div class="info-label">Joined</div><div class="info-value"><?= date('M d, Y',strtotime($user['date_of_joining'])) ?></div></div>
            <?php endif; ?>
            <div class="divider"></div>
            <button class="section-toggle-btn mb-3" onclick="toggleEl('allDetailsTable',this)" data-open="false">
              <i class="fas fa-chevron-down"></i> Show All Details
            </button>
            <div id="allDetailsTable" style="display:none">
              <div class="tbl-wrap">
                <table class="dash-table" style="font-size:11px">
                  <tbody>
                    <?php foreach ($existing_columns as $col): ?>
                      <?php if (!in_array($col,['photo','username','id','email','role','status','offer_accepted','offer_accepted_at','details_accepted','responsibilities_accepted','designation','department','mobileno','date_of_joining','reporting_manager'])): ?>
                        <tr>
                          <td style="font-weight:600;color:var(--muted);width:40%;font-size:10px;text-transform:uppercase;letter-spacing:.4px"><?= ucwords(str_replace('_',' ',$col)) ?></td>
                          <td><?php
                            $val = $user[$col] ?? null;
                            if ($val===null||$val===''||$val==='0000-00-00') echo '<span style="color:var(--muted)">—</span>';
                            elseif (in_array($col,['date_of_birth','date_of_joining','resignation_date','rejoin_date','anniversary_date'])) echo date("M d, Y",strtotime($val));
                            elseif (in_array($col,['responsibilities','address','kpi'])) echo nl2br(h($val));
                            else echo h($val);
                          ?></td>
                        </tr>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px">
              <?php if (($user['details_accepted']??'')!=='Accepted'): ?>
                <form method="POST" class="d-inline"><input type="hidden" name="action" value="accept_details">
                  <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check me-1"></i>Accept My Details</button></form>
              <?php else: ?>
                <span class="badge-custom badge-success"><i class="fas fa-check-circle me-1"></i>Details Accepted</span>
              <?php endif; ?>
              <?php if (!empty($user['responsibilities']) && ($user['responsibilities_accepted']??'')!=='Accepted'): ?>
                <form method="POST" class="d-inline"><input type="hidden" name="action" value="accept_responsibilities">
                  <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check me-1"></i>Accept Responsibilities</button></form>
              <?php elseif (!empty($user['responsibilities'])): ?>
                <span class="badge-custom badge-success"><i class="fas fa-check-circle me-1"></i>Responsibilities Accepted</span>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

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

        <!-- Monthly roll-up counters -->
        <div class="stats-row" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px">
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Check-ins</div><div style="font-size:22px;font-weight:800;color:var(--accent)"><?= $my_checkin_count ?></div><div style="font-size:10px;color:var(--muted)">this month</div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Check-outs</div><div style="font-size:22px;font-weight:800;color:var(--green)"><?= $my_checkout_count ?></div><div style="font-size:10px;color:var(--muted)">this month</div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Late</div><div style="font-size:22px;font-weight:800;color:var(--amber)"><?= $my_late_count ?></div><div style="font-size:10px;color:var(--muted)">after 9:30 AM</div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Half Days</div><div style="font-size:22px;font-weight:800;color:#1e3a8a"><?= $my_halfday_count ?></div><div style="font-size:10px;color:var(--muted)">checkout ≤ 1 PM</div></div>
          <!-- MONTHLY WORKING HOURS -->
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Monthly Hours</div><div style="font-size:22px;font-weight:800;color:var(--accent-2)"><?= $my_monthly_hours ? number_format((float)$my_monthly_hours['total_working_hours'],2) : '0.00' ?></div><div style="font-size:10px;color:var(--muted)"><?= $my_monthly_hours ? (int)$my_monthly_hours['total_working_days'] : 0 ?> working days</div></div>
        </div>

        <!-- MONTHLY CL -->
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px">
          <span class="badge-custom badge-info">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" class="btn-c" style="background:var(--amber);color:#fff;border:none;padding:9px 18px;border-radius:9px;font-weight:600;cursor:pointer" onclick="location.reload()"><i class="fas fa-redo"></i> Tap to Retry</button>
          </div>
          <div class="row g-3 mb-3">
            <div class="col-md-5">
              <label style="display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase">Location Type</label>
              <select id="ci_loc_type" class="form-control" style="padding:9px 12px;border:1px solid var(--border);border-radius:8px">
                <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 class="col-md-5" id="ciCliWrap" style="display:none">
              <label style="display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase">Client Name</label>
              <input type="text" id="ci_cli_name" class="form-control" style="padding:9px 12px;border:1px solid var(--border);border-radius:8px" 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="attVideo" 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="attCanvas"></canvas>
          <img id="attPreview" alt="Selfie preview">
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="btn btn-outline-primary btn-sm" id="ciCapBtn" onclick="ciCapture()" disabled><i class="fas fa-camera"></i> Capture Selfie</button>
            <button class="btn btn-outline-secondary btn-sm" id="ciRetakeBtn" style="display:none" onclick="ciRetake()"><i class="fas fa-rotate-left"></i> Retake</button>
            <button class="btn btn-primary btn-sm" id="ciSubmitBtn" style="display:none" onclick="ciSubmit()"><i class="fas fa-right-to-bracket"></i> Check In</button>
          </div>

        <?php elseif (!$my_checked_out): ?>
          <!-- CHECK-OUT (location only) -->
          <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="loc-status" id="coLocStatus"><i class="fas fa-spinner fa-spin"></i><span id="coLocStatusMsg">Getting location…</span></div>
          <p style="font-size:12.5px;color:var(--muted);margin-bottom:10px">You're checked in since <?= date('h:i A', strtotime($my_today['login_time'])) ?>. Capture your location to check out.</p>
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="btn btn-outline-primary btn-sm" id="coLocBtn" onclick="coCapLoc()"><i class="fas fa-location-dot"></i> Capture Location</button>
            <button class="btn btn-primary btn-sm" id="coSubmitBtn" disabled onclick="coSubmit()"><i class="fas fa-right-from-bracket"></i> Check Out</button>
          </div>

        <?php else: ?>
          <div style="text-align:center;padding:20px;color:var(--green)">
            <i class="fas fa-circle-check" style="font-size:1.8rem;margin-bottom:8px;display:block"></i>
            <strong>Today's attendance is complete.</strong>
            <div style="font-size:12px;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>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- CHANGE PASSWORD MODAL -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:var(--radius);border:none">
          <div class="modal-header" style="border-bottom:1px solid var(--border)">
            <h5 class="modal-title" style="font-weight:700;font-size:14px"><i class="fas fa-key me-2" style="color:var(--accent)"></i>Change Password</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <form method="POST">
            <input type="hidden" name="action" value="change_password">
            <div class="modal-body">
              <div class="mb-3">
                <label style="display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase">Current Password</label>
                <input type="password" name="current_password" class="form-control" required style="padding:9px 12px;border:1px solid var(--border);border-radius:8px">
              </div>
              <div class="mb-3">
                <label style="display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase">New Password</label>
                <input type="password" name="new_password" class="form-control" required minlength="6" style="padding:9px 12px;border:1px solid var(--border);border-radius:8px">
              </div>
              <div class="mb-1">
                <label style="display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase">Confirm New Password</label>
                <input type="password" name="confirm_password" class="form-control" required minlength="6" style="padding:9px 12px;border:1px solid var(--border);border-radius:8px">
              </div>
              <div style="font-size:11px;color:var(--muted);margin-top:6px">Minimum 6 characters.</div>
            </div>
            <div class="modal-footer" style="border-top:1px solid var(--border)">
              <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
              <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-save me-1"></i>Update Password</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- APPOINTMENT LETTER -->
    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-file-pdf"></i> Appointment Letter</div></div>
      <div class="dash-card-body">
        <?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 class="doc-item">
            <div class="doc-info">
              <div class="doc-icon"><i class="fas fa-file-pdf"></i></div>
              <div><div style="font-weight:600;font-size:13px">Appointment Letter</div><div style="font-size:11px;color:var(--muted)">PDF Document</div></div>
            </div>
            <div style="display:flex;gap:7px;flex-wrap:wrap;align-items:center">
              <a href="<?= h($offer_url_path) ?>" target="_blank" class="btn btn-primary btn-sm"><i class="fas fa-eye me-1"></i>View</a>
              <a href="<?= h($offer_url_path) ?>" download class="btn btn-success btn-sm"><i class="fas fa-download me-1"></i>Download</a>
              <?php if (($user['offer_accepted']??'')!=='Accepted'): ?>
                <form method="POST" class="d-inline"><input type="hidden" name="action" value="accept_offer">
                  <button type="submit" class="btn btn-warning btn-sm" onclick="return confirm('Accept?')"><i class="fas fa-check me-1"></i>Accept</button></form>
              <?php else: ?>
                <span class="badge-custom badge-success"><i class="fas fa-check-circle me-1"></i>Accepted</span>
              <?php endif; ?>
            </div>
          </div>
        <?php else: ?>
          <div class="alert-custom alert-info-custom"><i class="fas fa-info-circle me-2"></i>Appointment letter not available yet.</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- POLICY DOCUMENTS -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-book"></i> Employee Handbook &amp; Policy Documents</div>
        <?php if ($total_docs > 0): ?><span class="badge-custom badge-info"><?= $total_docs ?> docs</span><?php endif; ?>
      </div>
      <div class="dash-card-body">
        <?php if ($total_docs === 0): ?>
          <div class="alert-custom alert-info-custom"><i class="fas fa-info-circle me-2"></i>No documents available.</div>
        <?php else: ?>
          <div id="docsList">
            <?php foreach ($all_docs as $idx => $row):
              $status=$row['status']??'Not Acknowledged'; $isAck=$status==='Acknowledged';
              $badgeCls=$isAck?'badge-success':'badge-warning'; $isExtra=$idx>=3;
            ?>
              <div class="doc-item <?= $isExtra?'doc-extra':'' ?>" <?= $isExtra?'style="display:none"':'' ?>>
                <div class="doc-info">
                  <div class="doc-icon"><i class="fas fa-file-pdf"></i></div>
                  <div>
                    <div style="font-weight:600;font-size:13px"><?= h($row['title']) ?></div>
                    <span class="badge-custom <?= $badgeCls ?>" style="margin-top:2px"><i class="fas <?= $isAck?'fa-check-circle':'fa-clock' ?> me-1"></i><?= h($status) ?></span>
                  </div>
                </div>
                <div style="display:flex;gap:5px">
                  <a href="view_document.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-primary" target="_blank"><i class="fas fa-eye me-1"></i>View</a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          <?php if ($total_docs > 3): ?>
            <button class="show-more-btn" id="toggleDocsBtn" onclick="toggleDocs()">
              <i class="fas fa-chevron-down" id="toggleDocsIcon"></i>
              <span id="toggleDocsTxt">Show <?= $total_docs-3 ?> more documents</span>
            </button>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- KPI & PERFORMANCE -->
    <?php if (!empty($user['kpi'])||!empty($user['performance'])): ?>
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-chart-line"></i> KPI &amp; Performance</div>
        <?php if (!empty($user['kpi_status'])): ?><span class="badge-custom badge-purple"><?= h($user['kpi_status']) ?></span><?php endif; ?>
      </div>
      <div class="dash-card-body">
        <?php if (!empty($user['kpi'])): ?>
          <div style="margin-bottom:12px"><div style="font-size:11px;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:.5px;margin-bottom:7px"><i class="fas fa-bullseye me-1"></i>KPI</div><div class="kpi-box"><?= nl2br(h($user['kpi'])) ?></div></div>
        <?php endif; ?>
        <?php if (!empty($user['performance'])): ?>
          <div><div style="font-size:11px;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:.5px;margin-bottom:7px"><i class="fas fa-star me-1"></i>Performance</div><div class="kpi-box"><?= nl2br(h($user['performance'])) ?></div></div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- CAB -->
    <div class="dash-card" id="section-cab">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-money-check-alt"></i> CAB – Compensation &amp; Benefits</div></div>
      <div class="dash-card-body">

        <?php if (!empty($user['basic_salary'])): ?>
          <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:9px">Salary</div>
          <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:9px;margin-bottom:14px">
            <div class="salary-card"><small>Basic Salary</small><div class="amount">₹<?= number_format((float)$user['basic_salary'],2) ?></div></div>
            <?php if (!empty($user['previous_salary'])): ?>
            <div class="salary-card"><small>Previous Salary</small><div class="amount" style="color:var(--muted)">₹<?= number_format((float)$user['previous_salary'],2) ?></div></div>
            <?php endif; ?>
          </div>
          <div class="divider"></div>
        <?php endif; ?>

        <!-- Payslips -->
        <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:9px">Payslips <span class="badge-custom badge-info ms-1"><?= $payslip_count ?></span></div>
        <?php if ($result_payslips && $payslip_count > 0): ?>
          <div class="tbl-wrap" style="max-height:220px;overflow-y:auto;margin-bottom:14px">
            <table class="dash-table">
              <thead><tr><th>Month</th><th>Net Pay</th><th>Status</th><th></th></tr></thead>
              <tbody>
                <?php $result_payslips->data_seek(0); while ($p=$result_payslips->fetch_assoc()):
                  $rawM=$p['month']; $netPay=(float)($p['grand_total']??0);
                  $stRaw=strtolower(trim($p['status']??''));
                  $mLabel=preg_match('/^\d{4}-\d{2}$/',$rawM)?date('M Y',strtotime($rawM.'-01')):h($rawM);
                  $stClean=$payroll_has_status?($stRaw?:'draft'):'released';
                  $canView=!$payroll_has_status||in_array($stClean,['sent','approved','released','paid']);
                  $bCls=in_array($stClean,['approved','released','paid'])?'badge-success':(in_array($stClean,['rejected','cancelled'])?'badge-danger':'badge-warning');
                ?>
                  <tr>
                    <td><strong><?= $mLabel ?></strong></td>
                    <td style="font-family:'DM Mono',monospace;font-size:11px">₹<?= number_format($netPay,2) ?></td>
                    <td><span class="badge-custom <?= $bCls ?>"><?= ucfirst($stClean) ?></span></td>
                    <td><?php if ($canView): ?><a href="payslip.php?id=<?= urlencode($p['id']) ?>" class="btn btn-outline-primary btn-sm" target="_blank"><i class="fas fa-eye"></i></a><?php else: ?><small style="color:var(--muted)">Processing</small><?php endif; ?></td>
                  </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        <?php else: ?>
          <div class="alert-custom alert-info-custom mb-3"><i class="fas fa-info-circle me-2"></i>No payslips yet.</div>
        <?php endif; ?>

        <div class="divider"></div>

        <!-- Leave Balance (CL, SL, Comp Off) -->
        <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:9px"><i class="fas fa-umbrella-beach me-1"></i>My Leave Balance</div>
        <?php if (!empty($leave_balance_rows)): ?>
          <div class="leave-grid mb-3">
            <?php foreach ($leave_balance_rows as $lb):
              $label = $lb['leave_type']==='Compensatory' ? 'Comp Off' : $lb['leave_type'];
            ?>
              <div class="leave-bal-card">
                <div style="font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;margin-bottom:5px"><?= h($label) ?></div>
                <div style="font-size:24px;font-weight:700;font-family:'DM Mono',monospace;color:var(--accent)"><?= (int)$lb['balance'] ?></div>
                <div style="font-size:10px;color:var(--muted)">days</div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <div class="alert-custom alert-info-custom mb-3"><i class="fas fa-info-circle me-2"></i>Leave balance not configured.</div>
        <?php endif; ?>

        <div class="divider"></div>

        <!-- Holidays -->
        <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:9px"><i class="fas fa-calendar-check me-1"></i>Upcoming Holidays</div>
        <?php $total_holidays=count($holiday_rows); ?>
        <?php if (!empty($holiday_rows)): ?>
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead><tr><th>Date</th><th>Holiday</th><th>Location</th><th>Type</th></tr></thead>
              <tbody>
                <?php foreach ($holiday_rows as $i=>$hol): ?>
                  <tr class="<?= $i>=3?'extra-holiday':'' ?>" <?= $i>=3?'style="display:none"':'' ?>>
                    <td><strong style="font-size:11px"><?= date('M d, Y',strtotime($hol['holiday_date'])) ?></strong></td>
                    <td style="font-size:12px"><?= h($hol['name']) ?></td>
                    <td style="font-size:12px"><?= h($hol['location']??'All') ?></td>
                    <td><?= !empty($hol['is_optional'])?'<span class="badge-custom badge-warning">Optional</span>':'<span class="badge-custom badge-success">Mandatory</span>' ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <?php if ($total_holidays > 3): ?>
            <button class="show-more-btn mt-2" id="toggleHolidayBtn" onclick="toggleHolidays()">
              <i class="fas fa-chevron-down" id="toggleHolidayIcon"></i>
              <span id="toggleHolidayTxt">Show <?= $total_holidays-3 ?> more holidays</span>
            </button>
          <?php endif; ?>
        <?php else: ?>
          <div class="alert-custom alert-info-custom"><i class="fas fa-info-circle me-2"></i>No upcoming holidays.</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- TEAM LEAVE BALANCES (now includes Comp Off) -->
    <div class="dash-card">
      <div class="dash-card-header"><div class="dash-card-title"><i class="fas fa-users"></i> Team Leave Balances</div></div>
      <div class="dash-card-body">
        <?php if (empty($teamBalances)): ?>
          <div class="alert-custom alert-info-custom"><i class="fas fa-info-circle me-2"></i>No team members found.</div>
        <?php else: ?>
          <div class="leave-grid">
            <?php foreach ($teamBalances as $empId=>$b): ?>
              <div class="leave-bal-card">
                <strong style="font-size:12px"><?= h($b['name']) ?></strong>
                <div style="display:flex;gap:5px;justify-content:center;flex-wrap:wrap;margin-top:7px">
                  <span class="leave-badge" style="background:#dbeafe;color:#1e40af">CL: <?= $b['CL']??0 ?></span>
                  <span class="leave-badge" style="background:#fee2e2;color:#991b1b">SL: <?= $b['SL']??0 ?></span>
                  <span class="leave-badge" style="background:#ede9fe;color:#5b21b6">Comp Off: <?= $b['Compensatory']??0 ?></span>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- TEAM HIERARCHY -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-sitemap"></i> My Team Hierarchy</div>
        <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
          <span class="badge-custom badge-info">Team: <?= $total_team ?></span>
          <span class="badge-custom badge-success">Direct: <?= $direct ?></span>
          <span class="badge-custom badge-purple">Indirect: <?= $indirect ?></span>
        </div>
      </div>
      <div class="dash-card-body">
        <input type="text" id="orgSearch" class="form-control form-control-sm mb-3" placeholder="Search name, division..." onkeyup="filterOrgChart()" style="max-width:280px;font-size:13px">
        <div class="org-wrap">
          <div class="org-chart">
            <ul>
              <li class="level-l2" data-name="<?= h($manager_employee['full_name']) ?>">
                <div class="emp-card">
                  <div class="emp-photo-container">
                    <img src="<?= h($photo_url) ?>" class="emp-photo">
                  </div>
                  <div class="emp-details"><strong><?= h($manager_employee['full_name']) ?></strong><small>Manager</small></div>
                </div>
                <ul class="hierarchy-level"><?= buildHierarchy($hierarchy,$manager_key,$valid_locations,$base_url) ?></ul>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- PENDING LEAVES -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-umbrella-beach"></i> Pending Leave Approvals</div>
        <a href="leave_dashboard_manager.php" class="btn btn-sm btn-outline-primary" style="font-size:12px">View All</a>
      </div>
      <div class="dash-card-body">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Employee</th><th>Type</th><th>From</th><th>To</th><th>Action</th></tr></thead>
            <tbody>
              <?php $hasRows=false; while ($l=mysqli_fetch_assoc($leave_result)): $hasRows=true; ?>
                <tr>
                  <td><?= h($l['emp_name']) ?></td>
                  <td><span class="badge-custom badge-info"><?= h($l['leave_type']) ?></span></td>
                  <td style="font-size:12px"><?= h($l['start_date']) ?></td>
                  <td style="font-size:12px"><?= h($l['end_date']) ?></td>
                  <td>
                    <a href="leave_dashboard_manager.php?id=<?= $l['id'] ?>&action=approve" class="btn btn-sm btn-success" style="font-size:11px">Approve</a>
                    <a href="leave_dashboard_manager.php?id=<?= $l['id'] ?>&action=reject" class="btn btn-sm btn-danger ms-1" style="font-size:11px">Reject</a>
                  </td>
                </tr>
              <?php endwhile; ?>
              <?php if (!$hasRows): ?>
                <tr><td colspan="5" style="text-align:center;padding:20px;color:var(--muted)"><i class="fas fa-check-circle me-2" style="color:var(--green)"></i>No pending approvals</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- ═══ TEAM ATTENDANCE (daily_reports) ═══ -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-calendar"></i> Team Attendance</div>
        <form method="get" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
          <input type="hidden" name="month" value="<?= h($month) ?>">
          <input type="date" name="att_date" value="<?= h($att_date) ?>" class="form-control form-control-sm" style="width:150px;font-size:12px" onchange="this.form.submit()">
        </form>
      </div>
      <div class="dash-card-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:16px">
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Team Size</div><div style="font-size:20px;font-weight:800"><?= $team_size ?></div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Checked In</div><div style="font-size:20px;font-weight:800;color:var(--accent)"><?= $team_checked_in ?>/<?= $team_size ?></div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Checked Out</div><div style="font-size:20px;font-weight:800;color:var(--green)"><?= $team_checked_out ?>/<?= $team_size ?></div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Late</div><div style="font-size:20px;font-weight:800;color:var(--amber)"><?= $team_late_count ?></div></div>
          <div class="leave-bal-card"><div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:4px">Half Day</div><div style="font-size:20px;font-weight:800;color:#1e3a8a"><?= $team_halfday_count ?></div></div>
        </div>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Employee</th><th>Check-in</th><th>Check-out</th><th>Status</th><th>Photo</th><th>Detail</th></tr></thead>
            <tbody>
              <?php if (empty($att_rows)): ?>
                <tr><td colspan="6" style="text-align:center;padding:20px;color:var(--muted)">No team members found</td></tr>
              <?php else: foreach ($att_rows as $a): ?>
                <tr>
                  <td><div style="display:flex;align-items:center;gap:8px"><div class="emp-av"><?= strtoupper(substr($a['emp_name']??'?',0,1)) ?></div><strong style="font-size:12px"><?= h($a['emp_name']) ?></strong></div></td>
                  <td><?php if (!empty($a['login_time'])): ?><span class="mono"><?= date('h:i A', strtotime($a['login_time'])) ?></span><?php else: ?><span class="badge-custom badge-danger">Not Checked In</span><?php endif; ?></td>
                  <td><?php if (!empty($a['logout_time'])): ?><span class="mono"><?= date('h:i A', strtotime($a['logout_time'])) ?></span><?php else: ?><span style="color:var(--muted)">—</span><?php endif; ?></td>
                  <td>
                    <?php if (empty($a['login_time'])): ?>
                      <span class="pill pill-none">Absent</span>
                    <?php else: ?>
                      <?= $a['is_late'] ? '<span class="pill pill-late"><i class="fas fa-clock"></i> Late</span>' : '<span class="pill pill-ontime"><i class="fas fa-check"></i> On Time</span>' ?>
                      <?php if ($a['is_half_day']): ?><span class="pill pill-half"><i class="fas fa-hourglass-half"></i> Half Day</span><?php endif; ?>
                    <?php endif; ?>
                  </td>
                  <td><?= !empty($a['photo_path'])?'<a href="'.h($a['photo_path']).'" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-image"></i></a>':'—' ?></td>
                  <td><a href="dashboard_manager.php?detail_user=<?= $a['user_id'] ?>&month=<?= h($month) ?>&att_date=<?= h($att_date) ?>" class="btn btn-sm btn-outline-primary" style="font-size:11px">View Month</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- DAILY REPORTS -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-file-alt"></i> Latest Daily Reports</div>
        <a href="daily_reports_manager.php" class="btn btn-sm btn-outline-primary" style="font-size:12px">View All</a>
      </div>
      <div class="dash-card-body">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Date</th><th>Employee</th><th>Summary</th><th>Status</th><th>Action</th></tr></thead>
            <tbody>
              <?php $hasDr=false; while ($d=mysqli_fetch_assoc($daily_result)): $hasDr=true; ?>
                <tr>
                  <td style="font-size:11px;white-space:nowrap"><?= h($d['report_date']) ?></td>
                  <td style="font-size:12px"><?= h($d['emp_name']) ?></td>
                  <td style="max-width:160px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px"><?= h(substr($d['daily_summary']??'—',0,50)) ?></td>
                  <td><span class="badge-custom badge-info" style="font-size:10px"><?= h($d['report_status']) ?></span></td>
                  <td>
                    <a href="dashboard_manager.php?view_report=<?= $d['id'] ?>&month=<?= h($month) ?>" class="btn btn-sm btn-info" style="font-size:11px">View</a>
                    <form method="post" class="d-inline ms-1">
                      <input type="hidden" name="dr_id" value="<?= $d['id'] ?>">
                      <button type="submit" name="dr_action" value="approve" class="btn btn-success btn-sm" style="font-size:11px">✓</button>
                    </form>
                  </td>
                </tr>
              <?php endwhile; ?>
              <?php if (!$hasDr): ?><tr><td colspan="5" style="text-align:center;padding:20px;color:var(--muted)">No reports found</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>
</div>

<!-- MODALS -->
<?php if ($detail_user): ?>
<div class="modal fade show d-block" tabindex="-1" style="background:rgba(0,0,0,.55)">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="border-radius:var(--radius)">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-calendar-check me-2"></i>Attendance — <?= h($detail_name) ?> (<?= h($month) ?>)</h5>
        <a href="dashboard_manager.php?month=<?= h($month) ?>" class="btn-close"></a>
      </div>
      <div class="modal-body">
        <?php if (!empty($detail_monthly_hours)): ?>
        <div class="alert-custom alert-info-custom">
          <i class="fas fa-clock me-2"></i>
          Monthly total: <strong><?= number_format((float)$detail_monthly_hours['total_working_hours'],2) ?> hrs</strong>
          (<?= (int)$detail_monthly_hours['total_working_minutes'] ?> min) across
          <strong><?= (int)$detail_monthly_hours['total_working_days'] ?></strong> working days.
        </div>
        <?php endif; ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Date</th><th>Check-in</th><th>Check-out</th><th>Total Hours</th><th>Working Hours</th><th>Status</th><th>Map In</th><th>Map Out</th></tr></thead>
            <tbody>
              <?php foreach ($detail_rows as $r): ?>
                <tr>
                  <td style="font-size:12px"><?= date('d M Y', strtotime($r['report_date'])) ?></td>
                  <td style="font-size:12px"><?= !empty($r['login_time']) ? date('h:i A', strtotime($r['login_time'])) : '—' ?></td>
                  <td style="font-size:12px"><?= !empty($r['logout_time']) ? date('h:i A', strtotime($r['logout_time'])) : '—' ?></td>
                  <td style="font-family:'DM Mono',monospace;font-size:12px"><?= $r['total_hours'] ?? '—' ?></td>
                  <td style="font-family:'DM Mono',monospace;font-size:12px"><?= $r['daily_working_hours']!==null ? number_format((float)$r['daily_working_hours'],2) : '—' ?></td>
                  <td>
                    <?php if (empty($r['login_time'])): ?>
                      <span class="pill pill-none">Absent</span>
                    <?php else: ?>
                      <?= $r['is_late'] ? '<span class="pill pill-late">Late</span>' : '<span class="pill pill-ontime">On Time</span>' ?>
                      <?php if ($r['is_half_day']): ?><span class="pill pill-half">Half Day</span><?php endif; ?>
                    <?php endif; ?>
                  </td>
                  <td><?php if (!empty($r['latitude'])&&!empty($r['longitude'])): ?><a target="_blank" href="https://www.google.com/maps?q=<?= $r['latitude'] ?>,<?= $r['longitude'] ?>"><i class="fas fa-map-marker-alt text-danger"></i></a><?php else: ?>—<?php endif; ?></td>
                  <td><?php if (!empty($r['logout_latitude'])&&!empty($r['logout_longitude'])): ?><a target="_blank" href="https://www.google.com/maps?q=<?= $r['logout_latitude'] ?>,<?= $r['logout_longitude'] ?>"><i class="fas fa-map-marker-alt text-danger"></i></a><?php else: ?>—<?php endif; ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer"><a href="dashboard_manager.php?month=<?= h($month) ?>" class="btn btn-secondary">Close</a></div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if ($view_report && $report_row): ?>
<div class="modal fade show d-block" tabindex="-1" style="background:rgba(0,0,0,.55)">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="border-radius:var(--radius)">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-file-alt me-2"></i><?= h($report_row['emp_name']) ?> – <?= h($report_row['report_date']) ?></h5>
        <a href="dashboard_manager.php?month=<?= h($month) ?>" class="btn-close"></a>
      </div>
      <div class="modal-body">
        <?php foreach(['End of Day'=>$report_row['end_of_day_report']??'—','Daily Summary'=>$report_row['daily_summary']??'—','Manager Remarks'=>$report_row['manager_remarks']??'—'] as $label=>$val): ?>
          <div style="margin-bottom:12px">
            <div style="font-size:11px;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px"><?= $label ?></div>
            <div style="font-size:13px;color:var(--ink-2)"><?= nl2br(h($val)) ?></div>
          </div>
        <?php endforeach; ?>
      </div>
      <div class="modal-footer"><a href="dashboard_manager.php?month=<?= h($month) ?>" class="btn btn-secondary">Close</a></div>
    </div>
  </div>
</div>
<?php endif; ?>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ── SIDEBAR ── */
function toggleSidebar() {
  const sb=document.getElementById('sidebar'),ov=document.getElementById('sidebarOverlay');
  sb.classList.contains('open')?(sb.classList.remove('open'),ov.classList.remove('active')):(sb.classList.add('open'),ov.classList.add('active'));
}
function closeSidebar(){document.getElementById('sidebar').classList.remove('open');document.getElementById('sidebarOverlay').classList.remove('active');}
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeSidebar();});

/* ── TOGGLE DETAILS ── */
function toggleEl(id,btn){
  const el=document.getElementById(id),open=btn.dataset.open==='true';
  el.style.display=open?'none':'block';
  btn.dataset.open=!open;
  btn.querySelector('i').className=open?'fas fa-chevron-down':'fas fa-chevron-up';
}

/* ── DOCS TOGGLE ── */
let docsExpanded=false;
function toggleDocs(){
  docsExpanded=!docsExpanded;
  document.querySelectorAll('.doc-extra').forEach(el=>el.style.display=docsExpanded?'flex':'none');
  document.getElementById('toggleDocsIcon').className=docsExpanded?'fas fa-chevron-up':'fas fa-chevron-down';
  const count=<?= max(0,$total_docs-3) ?>;
  document.getElementById('toggleDocsTxt').textContent=docsExpanded?'Show fewer documents':`Show ${count} more documents`;
}

/* ── HOLIDAYS TOGGLE ── */
let holExpanded=false;
function toggleHolidays(){
  holExpanded=!holExpanded;
  document.querySelectorAll('.extra-holiday').forEach(el=>el.style.display=holExpanded?'':'none');
  document.getElementById('toggleHolidayIcon').className=holExpanded?'fas fa-chevron-up':'fas fa-chevron-down';
  const count=<?= max(0,$total_holidays-3) ?>;
  document.getElementById('toggleHolidayTxt').textContent=holExpanded?'Show fewer holidays':`Show ${count} more holidays`;
}

/* ── ORG CHART ── */
function filterOrgChart(){
  const q=document.getElementById('orgSearch').value.toLowerCase();
  document.querySelectorAll('.org-chart li').forEach(li=>{
    const text=((li.dataset.name||'')+(li.dataset.division||'')+(li.dataset.location||'')).toLowerCase();
    li.style.display=q===''||text.includes(q)?'':'none';
  });
}
document.addEventListener('DOMContentLoaded',function(){
  document.querySelectorAll('.toggle-icon').forEach(icon=>{
    const ul=icon.closest('li').querySelector('.hierarchy-level');
    if (!ul) return;
    icon.addEventListener('click',function(e){
      e.stopPropagation();
      const collapsed=ul.style.display==='none';
      ul.style.display=collapsed?'':'none';
      icon.querySelector('i').className=collapsed?'fas fa-chevron-up':'fas fa-chevron-down';
    });
  });
});

/* ══════════════════════════════════════════════
   CHECK-IN CAMERA + LOCATION
══════════════════════════════════════════════ */
var ciVideo=document.getElementById('attVideo');
var ciCanvas=document.getElementById('attCanvas');
var ciPreview=document.getElementById('attPreview');
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 LOCATION CAPTURE
══════════════════════════════════════════════ */
var coEveLoc=false;
async function coCapLoc(){
  var btn=document.getElementById('coLocBtn');
  var locStatus=document.getElementById('coLocStatus');
  var locStatusMsg=document.getElementById('coLocStatusMsg');
  if(btn){ btn.disabled=true; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Getting…'; }
  if(locStatus){ locStatus.className='loc-status getting'; locStatusMsg.textContent='Getting your location…'; }
  try{
    const l=await getLoc();
    window.__coLat=l.lat; window.__coLng=l.lng;
    coEveLoc=true; document.getElementById('coSubmitBtn').disabled=false;
    if(btn){ btn.innerHTML='<i class="fas fa-check-circle"></i> Location Captured'; btn.classList.remove('btn-outline-primary'); btn.classList.add('btn-success'); btn.disabled=false; }
    if(locStatus){ locStatus.className='loc-status got'; locStatusMsg.textContent='Location captured successfully.'; }
  }catch(e){
    if(btn){ btn.disabled=false; btn.innerHTML='<i class="fas fa-location-dot"></i> Retry Location'; }
    if(locStatus){ locStatus.className='loc-status failed'; locStatusMsg.textContent='Could not get location. Tap Retry Location.'; }
    coEveLoc=false;
  }
}
function coSubmit(){
  if(!coEveLoc){ var el=document.getElementById('coError'),ml=document.getElementById('coErrorMsg'); ml.textContent='Capture location first.'; el.classList.add('show'); setTimeout(()=>el.classList.remove('show'),6000); return; }
  document.getElementById('loadingText').textContent='Checking out…';
  document.getElementById('loadingOverlay').classList.add('show');
  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',window.__coLat||''); add('lng',window.__coLng||'');
  document.body.appendChild(f); f.submit();
}
</script>
</body>
</html>
<?php $conn->close(); ?>