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

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

$uid   = $_SESSION['user_id'];   // NOTE: daily_reports.user_id is varchar(11) -> always bind as "s"
$today = date('Y-m-d');
$msg   = $msg_type = '';

/*
 * FIX (matches the proven-correct pattern from myteam.php):
 *
 * This file previously filtered every team/report query by ONLY
 * LOWER(u.reporting_manager) = LOWER($manager_username). Some
 * employees have reporting_manager stored as the manager's FULL
 * NAME instead of their username, so they were silently excluded
 * from Pending Approvals, History, Export, and the Employee filter
 * dropdown.
 *
 * We now match on username OR full name (case-insensitive,
 * whitespace-safe), exactly like myteam.php, and build this
 * condition once so every query below stays consistent.
 */
$manager_username = trim($_SESSION['username'] ?? '');

$mgr_stmt = $conn->prepare("SELECT CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,'')) AS name FROM users WHERE id = ?");
$mgr_stmt->bind_param("s", $uid);
$mgr_stmt->execute();
$manager_name = trim($mgr_stmt->get_result()->fetch_assoc()['name'] ?? '') ?: $manager_username;
$mgr_stmt->close();

// Reusable match condition: reporting_manager equals the manager's
// username OR their full name (case-insensitive, whitespace-safe).
const MGR_MATCH_SQL = "(LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)))";
// Same condition, for queries that don't alias the users table as `u`.
const MGR_MATCH_SQL_NOALIAS = "(LOWER(TRIM(reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(reporting_manager)) = LOWER(TRIM(?)))";

/**
 * Small helper to cut repeated prepare/bind/execute/error-check boilerplate.
 * Returns [true, ''] on success or [false, error message] on failure.
 */
function run($conn, $sql, $types = '', ...$params) {
    $s = $conn->prepare($sql);
    if (!$s) return [false, $conn->error];
    if ($types !== '') $s->bind_param($types, ...$params);
    $ok  = $s->execute();
    $err = $s->error;
    $s->close();
    return [$ok, $err];
}

// ── POST HANDLERS ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';

    if ($act === 'approve_report' && in_array($_POST['new_status'] ?? '', ['Approved', 'Rejected'])) {
        $report_user_id = $_POST['report_user_id'] ?? '';
        // A manager should never approve/reject their own record via this action.
        if ($report_user_id === '' || $report_user_id == $uid) {
            $msg = "Invalid report reference."; $msg_type = 'danger';
        } else {
            /*
             * AUTHORIZATION CHECK (fix):
             * The team-scoping filters on the Pending/History/Export queries only
             * control what the manager *sees*. Without this check, a manager could
             * still POST an arbitrary report_user_id belonging to an employee
             * outside their team and approve/reject that report directly, since
             * the UPDATE below has no ownership condition of its own.
             * We verify the target employee's reporting_manager matches this
             * manager's username OR full name (case-insensitive) -- same
             * matching rule used everywhere else in this file.
             */
            $chk = $conn->prepare("SELECT id FROM users WHERE id=? AND " . MGR_MATCH_SQL_NOALIAS);
            $chk->bind_param("sss", $report_user_id, $manager_username, $manager_name);
            $chk->execute();
            $is_team_member = $chk->get_result()->fetch_assoc();
            $chk->close();

            if (!$is_team_member) {
                $msg = "You are not authorized to approve/reject this employee's report.";
                $msg_type = 'danger';
            } else {
                [$ok, $err] = run(
                    $conn,
                    "UPDATE daily_reports SET approval_status=?, manager_remark=? WHERE user_id=? AND report_date=?",
                    "ssss",
                    $_POST['new_status'], $_POST['manager_remark'], $report_user_id, $_POST['report_date']
                );
                if ($ok) { $msg = "Report {$_POST['new_status']} successfully."; $msg_type = 'success'; }
                else     { $msg = "Failed to update report: $err"; $msg_type = 'danger'; }
            }
        }
    }

    if ($act === 'morning') {
        $photo_path = '';
        if (empty($_POST['photo_data'])) {
            $msg = "Selfie photo is required."; $msg_type = 'danger';
        } else {
            $dir = 'uploads/attendance/';
            if (!is_dir($dir)) mkdir($dir, 0777, true);
            $photo_path = $dir . $uid . '_morning_' . date('Ymd_His') . '.jpg';
            $raw = base64_decode(str_replace(['data:image/jpeg;base64,', ' '], ['', '+'], $_POST['photo_data']));
            if (file_put_contents($photo_path, $raw) === false) {
                $msg = "Failed to save photo."; $msg_type = 'danger'; $photo_path = '';
            }
        }

        if (empty($msg)) {
            $loc = $_POST['location_type'] ?? '';
            $cl  = trim($_POST['client_name'] ?? '');
            $mr  = trim($_POST['morning'] ?? '');
            $lat = $_POST['lat'] ?? null;
            $lng = $_POST['lng'] ?? null;

            /*
             * `Location` and `Name of the Client` are NOT NULL columns with
             * no default. Map location_type -> Location enum and
             * client_name -> `Name of the Client` (with a safe fallback) so
             * the NOT NULL constraint is always satisfied.
             */
            $location_enum_map = [
                'Office'         => 'Corporate Office',
                'Client Visit'   => 'Client Office',
                'Field Work'     => 'Corporate Office',
                'Work From Home' => 'Work from Home',
            ];
            $location_enum  = $location_enum_map[$loc] ?? 'Corporate Office';
            $name_of_client = ($cl !== '') ? $cl : 'N/A';

            [$ok, $err] = run(
                $conn,
                "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 (?,?,?,?,?,?,?,?,?,?,NOW(),'Pending')
                 ON DUPLICATE KEY UPDATE
                    Location             = VALUES(Location),
                    `Name of the Client` = VALUES(`Name of the Client`),
                    Morning              = VALUES(Morning),
                    location_type        = VALUES(location_type),
                    client_name          = VALUES(client_name),
                    latitude             = VALUES(latitude),
                    longitude            = VALUES(longitude),
                    photo_path           = VALUES(photo_path),
                    login_time           = NOW(),
                    approval_status      = 'Pending'",
                "sssssssdds",
                $uid, $today, $location_enum, $name_of_client, $mr,
                $loc, $cl, $lat, $lng, $photo_path
            );

            if ($ok) {
                header("Location: manager_daily_report.php"); exit();
            } else {
                $msg = "Failed to save report: $err"; $msg_type = 'danger';
            }
        }
    }

    if ($act === 'evening') {
        [$ok, $err] = run(
            $conn,
            "UPDATE daily_reports SET Hits=?,Missed=?,`carry forward`=?,daily_summary=?,logout_latitude=?,logout_longitude=?,logout_time=NOW(),approval_status='Pending' WHERE user_id=? AND report_date=?",
            "ssssddss",
            $_POST['hits'], $_POST['missed'], $_POST['carry_forward'], $_POST['daily_summary'],
            $_POST['lat'], $_POST['lng'], $uid, $today
        );
        if ($ok) { header("Location: manager_daily_report.php"); exit(); }
        $msg = "Failed to save evening report: $err"; $msg_type = 'danger';
    }

    if ($act === 'edit_own') {
        [$ok, $err] = run(
            $conn,
            "UPDATE daily_reports SET Morning=?,Hits=?,Missed=?,`carry forward`=?,daily_summary=?,location_type=?,client_name=?,approval_status='Pending' WHERE user_id=? AND report_date=?",
            "sssssssss",
            $_POST['morning'], $_POST['hits'], $_POST['missed'], $_POST['carry_forward'], $_POST['daily_summary'],
            $_POST['location_type'], $_POST['client_name'], $uid, $_POST['report_date']
        );
        if ($ok) { $msg = "Report updated. Status reset to Pending."; $msg_type = 'success'; }
        else     { $msg = "Failed to update report: $err"; $msg_type = 'danger'; }
    }

    /*
     * NEW: "My Report History" — Add / Update.
     * Lets the manager create a brand-new own-report entry for any date
     * (e.g. a day they forgot to log), or update an existing own entry,
     * straight from the My Report History card. Uses INSERT ... ON
     * DUPLICATE KEY UPDATE against (user_id, report_date), same pattern
     * as the "morning" handler above, so it works whether or not a row
     * already exists for that date. Editing is blocked once a record is
     * already Approved, to keep locked/approved history immutable.
     */
    if ($act === 'save_own_report') {
        $rdate = trim($_POST['report_date'] ?? '');
        if ($rdate === '') {
            $msg = "Report date is required."; $msg_type = 'danger';
        } else {
            $lock_chk = $conn->prepare("SELECT approval_status FROM daily_reports WHERE user_id=? AND report_date=?");
            $lock_chk->bind_param("ss", $uid, $rdate);
            $lock_chk->execute();
            $lock_row = $lock_chk->get_result()->fetch_assoc();
            $lock_chk->close();

            if (($lock_row['approval_status'] ?? '') === 'Approved') {
                $msg = "This report is already Approved and locked, so it can't be edited.";
                $msg_type = 'danger';
            } else {
                $loc = $_POST['location_type'] ?? '';
                $cl  = trim($_POST['client_name'] ?? '');

                // Same NOT NULL-safe enum mapping used by the "morning" handler.
                $location_enum_map = [
                    'Office'         => 'Corporate Office',
                    'Client Visit'   => 'Client Office',
                    'Field Work'     => 'Corporate Office',
                    'Work From Home' => 'Work from Home',
                ];
                $location_enum  = $location_enum_map[$loc] ?? 'Corporate Office';
                $name_of_client = ($cl !== '') ? $cl : 'N/A';

                [$ok, $err] = run(
                    $conn,
                    "INSERT INTO daily_reports
                        (user_id, report_date, Location, `Name of the Client`, Morning, Hits, Missed,
                         `carry forward`, daily_summary, location_type, client_name, approval_status)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,'Pending')
                     ON DUPLICATE KEY UPDATE
                        Location             = VALUES(Location),
                        `Name of the Client` = VALUES(`Name of the Client`),
                        Morning              = VALUES(Morning),
                        Hits                 = VALUES(Hits),
                        Missed               = VALUES(Missed),
                        `carry forward`      = VALUES(`carry forward`),
                        daily_summary        = VALUES(daily_summary),
                        location_type        = VALUES(location_type),
                        client_name          = VALUES(client_name),
                        approval_status      = 'Pending'",
                    "sssssssssss",
                    $uid, $rdate, $location_enum, $name_of_client,
                    trim($_POST['morning'] ?? ''), trim($_POST['hits'] ?? ''), trim($_POST['missed'] ?? ''),
                    trim($_POST['carry_forward'] ?? ''), trim($_POST['daily_summary'] ?? ''),
                    $loc, $cl
                );

                if ($ok) {
                    $msg = "Report for " . date('d M Y', strtotime($rdate)) . " saved successfully.";
                    $msg_type = 'success';
                } else {
                    $msg = "Failed to save report: $err"; $msg_type = 'danger';
                }
            }
        }
    }
}

// ── TODAY'S OWN RECORD ── (user_id is varchar -> bind as string, not int)
$s = $conn->prepare("SELECT * FROM daily_reports WHERE user_id=? AND report_date=?");
$s->bind_param("ss", $uid, $today); $s->execute();
$own = $s->get_result()->fetch_assoc() ?? []; $s->close();
$morning_done = !empty($own['Morning']) || !empty($own['login_time']);
$evening_done = !empty($own['logout_time']);
$locked       = ($own['approval_status'] ?? '') === 'Approved';

// ── FILTER ──
$view = $_GET['view'] ?? 'month'; $from = $_GET['from'] ?? ''; $to = $_GET['to'] ?? '';
$emp_f = $_GET['employee'] ?? ''; $st_f = $_GET['status'] ?? '';
if ($from && $to) { $start = $from; $end = $to; }
elseif ($view === 'today') { $start = $end = $today; }
elseif ($view === 'week') { $start = date('Y-m-d', strtotime('monday this week')); $end = date('Y-m-d', strtotime('sunday this week')); }
else { $start = date('Y-m-01'); $end = date('Y-m-t'); }

// ── EXPORT ──
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $wh = "report_date BETWEEN ? AND ? AND " . MGR_MATCH_SQL; $pr = [$start, $end, $manager_username, $manager_name]; $tp = "ssss";
    if ($emp_f) { $wh .= " AND dr.user_id=?"; $tp .= "s"; $pr[] = $emp_f; }
    if ($st_f)  { $wh .= " AND approval_status=?"; $tp .= "s"; $pr[] = $st_f; }
    $s = $conn->prepare("SELECT dr.*,u.username AS ename FROM daily_reports dr INNER JOIN users u ON dr.user_id=u.id WHERE $wh ORDER BY report_date DESC");
    $s->bind_param($tp, ...$pr); $s->execute(); $res = $s->get_result();
}

// ── PENDING TEAM REPORTS (only this manager's team, excluding own record) ──
$s = $conn->prepare("SELECT dr.*,u.username AS ename FROM daily_reports dr INNER JOIN users u ON dr.user_id=u.id WHERE dr.approval_status='Pending' AND dr.user_id!=? AND " . MGR_MATCH_SQL . " ORDER BY dr.report_date DESC");
$s->bind_param("sss", $uid, $manager_username, $manager_name); $s->execute();
$pending = $s->get_result()->fetch_all(MYSQLI_ASSOC); $s->close();

// ── EMPLOYEES FOR FILTER (only this manager's team) ──
$s = $conn->prepare("SELECT id,username FROM users WHERE role='employee' AND " . MGR_MATCH_SQL_NOALIAS . " ORDER BY username");
$s->bind_param("ss", $manager_username, $manager_name); $s->execute();
$all_emp = $s->get_result()->fetch_all(MYSQLI_ASSOC); $s->close();

// ── HISTORY (only this manager's team) ──
$wh = "report_date BETWEEN ? AND ? AND " . MGR_MATCH_SQL; $pr = [$start, $end, $manager_username, $manager_name]; $tp = "ssss";
if ($emp_f) { $wh .= " AND dr.user_id=?"; $tp .= "s"; $pr[] = $emp_f; }
if ($st_f)  { $wh .= " AND approval_status=?"; $tp .= "s"; $pr[] = $st_f; }
$s = $conn->prepare("SELECT dr.*,u.username AS ename FROM daily_reports dr INNER JOIN users u ON dr.user_id=u.id WHERE $wh ORDER BY report_date DESC");
$s->bind_param($tp, ...$pr); $s->execute();
$reports = $s->get_result()->fetch_all(MYSQLI_ASSOC); $s->close();

$total = $approved = $rejected = $pend_cnt = 0;
foreach ($reports as $r) {
    $total++;
    $st = $r['approval_status'] ?? 'Pending';
    if ($st === 'Approved') $approved++;
    elseif ($st === 'Rejected') $rejected++;
    else $pend_cnt++;
}

/*
 * NEW: "My Report History" — the manager's OWN daily reports over the
 * selected date range. This is intentionally separate from the team
 * $reports query above (which is scoped to reporting_manager matches
 * and therefore never includes the manager's own rows). Re-uses the
 * same $start/$end/$st_f filter values already computed above.
 */
$my_wh = "user_id=? AND report_date BETWEEN ? AND ?"; $my_pr = [$uid, $start, $end]; $my_tp = "sss";
if ($st_f) { $my_wh .= " AND approval_status=?"; $my_tp .= "s"; $my_pr[] = $st_f; }
$s = $conn->prepare("SELECT * FROM daily_reports WHERE $my_wh ORDER BY report_date DESC");
$s->bind_param($my_tp, ...$my_pr); $s->execute();
$my_reports = $s->get_result()->fetch_all(MYSQLI_ASSOC); $s->close();

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
$username_session = $_SESSION['username'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>MPC · Daily Reports</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,wght@0,300;0,400;0,500;0,600;0,700;1,400&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 ─── */
.layout{display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:var(--sidebar-bg);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.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:8px 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:15px;text-align:center;font-size:12px;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:10px 8px;border-top:1px solid rgba(255,255,255,.06)}

/* ─── CONTENT ─── */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s ease}
.content.expanded{margin-left:0}

/* ─── TOPBAR ─── */
.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 22px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:34px;height:34px;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:14px;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)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}
.topbar-badge{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;background:#fef3c7;color:#92400e}
.dot-pulse{width:6px;height:6px;border-radius:50%;background:var(--amber);animation:dp 1.5s infinite;flex-shrink:0}
@keyframes dp{0%,100%{opacity:1}50%{opacity:.3}}

/* ─── PAGE ─── */
.page{padding:22px;flex:1}
.page-header{margin-bottom:22px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-top:2px}

/* ─── ALERTS ─── */
.alert-custom{padding:12px 16px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:14px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}
.alert-error-custom{background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}
.alert-warning-custom{background:#fef3c7;border-left:3px solid var(--amber);color:#78350f}

/* ─── INLINE ERROR — form validation, no permission banners ─── */
.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;animation:fadeIn .2s ease}
.inline-error.show{display:flex}
.inline-error.warning{background:#fef3c7;border-left-color:var(--amber);color:#78350f}
@keyframes fadeIn{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}

/* ─── STAT CARDS ─── */
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-bottom:22px}
.scard{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px;box-shadow:var(--shadow);display:flex;align-items:center;gap:14px;transition:transform .2s,box-shadow .2s;position:relative;overflow:hidden}
.scard:hover{transform:translateY(-2px);box-shadow:var(--shadow-md)}
.scard::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:3px 3px 0 0}
.scard.blue::before{background:var(--accent)}.scard.green::before{background:var(--green)}
.scard.red::before{background:var(--red)}.scard.amber::before{background:var(--amber)}
.si{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0}
.si.blue{background:#ede9fe;color:var(--accent)}.si.green{background:#d1fae5;color:var(--green)}
.si.red{background:#fee2e2;color:var(--red)}.si.amber{background:#fef3c7;color:var(--amber)}
.sv{font-size:1.7rem;font-weight:800;line-height:1;color:var(--ink)}
.sl{font-size:.72rem;color:var(--muted);font-weight:600;margin-top:3px;text-transform:uppercase;letter-spacing:.4px}

/* ─── DASH CARDS ─── */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:18px}
.dash-card-header{padding:16px 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:14px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:13px}
.dash-card-body{padding:18px}

/* ─── 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.locked{background:#f59e0b;border-color:#f59e0b;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}

/* ─── BADGES ─── */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.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}

/* ─── TABLE ─── */
.tbl-wrap{overflow-x:auto}
.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:11px;text-transform:uppercase;letter-spacing:.6px;padding:10px 14px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 14px;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}
.trunc{max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block;cursor:help}
.mono{font-family:'DM Mono',monospace;font-size:12px}

/* ─── FORM ELEMENTS ─── */
.form-field{margin-bottom:14px}
.form-field label{display:block;font-size:12px;font-weight:600;color:var(--ink-2);margin-bottom:5px;text-transform:uppercase;letter-spacing:.3px}
.form-field label span{color:var(--red)}
.field-control{width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;color:var(--ink);background:var(--surface);outline:none;transition:border-color .2s,box-shadow .2s;font-family:inherit}
.field-control:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(79,70,229,.1)}
.field-control::placeholder{color:var(--muted)}
textarea.field-control{resize:vertical;min-height:70px}

/* ─── BUTTONS ─── */
.btn-c{display:inline-flex;align-items:center;gap:7px;padding:9px 18px;border-radius:9px;font-size:13px;font-weight:600;border:none;cursor:pointer;transition:all .2s;text-decoration:none;font-family:inherit;white-space:nowrap}
.btn-c:hover{transform:translateY(-1px)}
.btn-primary-c{background:var(--accent);color:#fff;box-shadow:0 2px 8px rgba(79,70,229,.25)}
.btn-primary-c:hover{background:#4338ca;color:#fff}
.btn-success-c{background:var(--green);color:#fff}
.btn-success-c:hover{background:#047857;color:#fff}
.btn-amber-c{background:var(--amber);color:#fff}
.btn-amber-c:hover{background:#b45309;color:#fff}
.btn-outline-c{background:var(--surface);color:var(--ink-2);border:1px solid var(--border)}
.btn-outline-c:hover{border-color:var(--accent);color:var(--accent)}
.btn-sm-c{padding:6px 12px;font-size:12px;border-radius:7px}
.btn-xs-c{padding:4px 10px;font-size:11px;border-radius:6px}
.btn-c:disabled{opacity:.45;cursor:not-allowed;transform:none !important}

/* ─── MAP LINK ─── */
.map-lnk{display:inline-flex;align-items:center;gap:3px;color:var(--accent);font-size:12px;font-weight:600;text-decoration:none}
.map-lnk:hover{text-decoration:underline}

/* ─── STATUS BADGES ─── */
.pill{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:50px;font-size:11px;font-weight:700}
.pill-pend{background:#fef3c7;color:#78350f}
.pill-appr{background:#d1fae5;color:#065f46}
.pill-reje{background:#fee2e2;color:#7f1d1d}

/* ─── CAMERA (robust, with visible error/retry option) ─── */
.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}
#video{width:100%;max-height:300px;object-fit:cover;display:block;border-radius:var(--radius-sm)}
#canvas{display:none}
#preview{width:100%;max-height:240px;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}

/* ─── LOCATION STATUS BAR ─── */
.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 ─── */
.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}

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

/* ─── RESPONSIVE ─── */
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}
  .content{margin-left:0}.page{padding:14px}
  .stats-grid{grid-template-columns:repeat(2,1fr)}
}


/* ═══ MOBILE SIDEBAR FIX - SAME AS DASHBOARD_MANAGER ═══ */
.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}
@media(max-width:768px){
  body{overflow-x:hidden}
  .layout{min-width:0;width:100%}
  .sidebar{transform:translateX(-100%) !important;left:0;top:0;bottom:0;height:100vh;z-index:300}
  .sidebar.open{transform:translateX(0) !important}
  .content{margin-left:0 !important;width:100%;max-width:100%;min-width:0}
  .content.expanded{margin-left:0 !important}
  .topbar{padding:0 12px;gap:8px}
  .page{padding:13px !important}
  .topbar-user span{max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay.active{display:none !important;opacity:0 !important}
  .content{margin-left:var(--sidebar-w)}
}

</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>

  <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"><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 active"><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="tasks_manager.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="manager_expenses.php" class="nav-link"><i class="fas fa-receipt"></i> 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="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()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">Daily Reports</span>
    </div>
    <div class="topbar-spacer"></div>
    <?php if (!empty($pending)): ?>
      <div class="topbar-badge"><span class="dot-pulse"></span><?= count($pending) ?> Pending</div>
    <?php endif; ?>
    <div class="topbar-user" style="margin-left:10px">
      <div class="topbar-avatar"><?= strtoupper(substr($username_session, 0, 1)) ?></div>
      <span><?= h(explode(' ', $username_session)[0]) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">Daily Reports</div>
      <div class="page-subtitle"><?= date('l, F j, Y') ?> · Attendance & report management</div>
    </div>

    <?php if ($msg): ?>
      <div class="alert-custom <?= $msg_type==='success'?'alert-success-custom':($msg_type==='warning'?'alert-warning-custom':'alert-error-custom') ?>">
        <i class="fas fa-<?= $msg_type==='success'?'check-circle':'times-circle' ?> me-2"></i><?= h($msg) ?>
      </div>
    <?php endif; ?>

    <!-- ─── STAT CARDS ─── -->
    <div class="stats-grid">
      <div class="scard blue"><div class="si blue"><i class="fas fa-file-lines"></i></div><div><div class="sv"><?= $total ?></div><div class="sl">Total</div></div></div>
      <div class="scard green"><div class="si green"><i class="fas fa-circle-check"></i></div><div><div class="sv"><?= $approved ?></div><div class="sl">Approved</div></div></div>
      <div class="scard amber"><div class="si amber"><i class="fas fa-clock"></i></div><div><div class="sv"><?= $pend_cnt ?></div><div class="sl">Pending</div></div></div>
      <div class="scard red"><div class="si red"><i class="fas fa-circle-xmark"></i></div><div><div class="sv"><?= $rejected ?></div><div class="sl">Rejected</div></div></div>
    </div>

    <!-- ─── MY ATTENDANCE TODAY ─── -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-fingerprint"></i> My Attendance Today</div>
        <div style="display:flex;align-items:center;gap:8px">
          <span class="mono" style="color:var(--muted)"><?= date('D, d M Y') ?></span>
          <?php
            if ($locked) echo '<span class="badge-custom badge-success"><i class="fas fa-lock me-1"></i>Approved & Locked</span>';
            elseif ($morning_done && $evening_done) echo '<span class="badge-custom badge-warning">Pending Review</span>';
            elseif ($morning_done) echo '<span class="badge-custom badge-info">Evening Pending</span>';
            else echo '<span class="badge-custom badge-danger">Not Started</span>';
          ?>
        </div>
      </div>
      <div class="dash-card-body">

      <!-- Status track -->
      <div class="status-track">
        <div class="status-step">
          <div class="step-dot <?= $morning_done?($locked?'locked':'done'):'active' ?>">
            <i class="fas <?= $morning_done?'fa-check':'fa-sun' ?>"></i>
          </div>
          <div class="step-label">Morning</div>
          <?php if (!empty($own['login_time'])): ?>
            <div class="step-time"><?= date('h:i A', strtotime($own['login_time'])) ?></div>
          <?php endif; ?>
        </div>
        <div class="status-step">
          <div class="step-dot <?= $evening_done?($locked?'locked':'done'):($morning_done?'active':'') ?>">
            <i class="fas <?= $evening_done?'fa-check':'fa-moon' ?>"></i>
          </div>
          <div class="step-label">Evening</div>
          <?php if (!empty($own['logout_time'])): ?>
            <div class="step-time"><?= date('h:i A', strtotime($own['logout_time'])) ?></div>
          <?php endif; ?>
        </div>
        <div class="status-step">
          <div class="step-dot <?= $locked?'locked':'' ?>">
            <i class="fas <?= $locked?'fa-lock':'fa-shield-halved' ?>"></i>
          </div>
          <div class="step-label">Approved</div>
        </div>
      </div>

      <?php if ($locked): ?>
        <div style="text-align:center;padding:24px;color:var(--green)">
          <i class="fas fa-lock-open" style="font-size:2rem;margin-bottom:10px;display:block"></i>
          <strong>Today's record is Approved &amp; Locked</strong>
        </div>

      <?php elseif (!$morning_done): ?>
        <!-- MORNING FORM: attendance option with robust camera + location capture -->
        <div id="morningSection">
          <div class="inline-error" id="morningError">
            <i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i>
            <span id="morningErrorMsg"></span>
          </div>

          <div class="camera-error-box" id="cameraErrorBox">
            <i class="fas fa-video-slash"></i>
            <p id="cameraErrorMsg">Camera could not start.</p>
            <button type="button" class="btn-c btn-amber-c" 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">
              <div class="form-field">
                <label>Location Type <span>*</span></label>
                <select id="loc_type" class="field-control" required>
                  <option value="">Select Location</option>
                  <option>Office</option><option>Client Visit</option>
                  <option>Field Work</option><option>Work From Home</option>
                </select>
              </div>
            </div>
            <div class="col-md-5" id="cliWrap" style="display:none">
              <div class="form-field">
                <label>Client Name</label>
                <input type="text" id="cli_name" class="field-control" placeholder="Enter client name">
              </div>
            </div>
          </div>
          <div class="form-field">
            <label>Morning Plan <span>*</span></label>
            <textarea id="morning_txt" class="field-control" rows="3" placeholder="Your plan for today…" required></textarea>
          </div>

          <div class="camera-wrap" id="cameraWrap">
            <div class="camera-loading" id="cameraLoading">
              <i class="fas fa-circle-notch"></i>
              <span>Starting camera…</span>
            </div>
            <video id="video" autoplay playsinline muted style="display:none"></video>
            <div class="camera-overlay" id="cameraOverlay" style="display:none"><i class="fas fa-circle" style="color:#ef4444;font-size:8px"></i> Live</div>
          </div>
          <canvas id="canvas" style="display:none"></canvas>
          <img id="preview" alt="Selfie preview">

          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button class="btn-c btn-outline-c" id="capBtn" onclick="capPhoto()" disabled><i class="fas fa-camera"></i> Capture Selfie</button>
            <button class="btn-c btn-outline-c" id="retakeBtn" style="display:none" onclick="retake()"><i class="fas fa-rotate-left"></i> Retake</button>
            <button class="btn-c btn-primary-c" id="subMorn" style="display:none" onclick="submitMorn()"><i class="fas fa-right-to-bracket"></i> Submit Morning</button>
          </div>
        </div>

      <?php elseif (!$evening_done): ?>
        <!-- EVENING FORM: attendance option with explicit location capture -->
        <div class="inline-error" id="eveningError">
          <i class="fas fa-exclamation-circle" style="margin-top:1px;flex-shrink:0"></i>
          <span id="eveningErrorMsg"></span>
        </div>
        <div class="loc-status" id="locStatus">
          <i class="fas fa-spinner fa-spin"></i>
          <span id="locStatusMsg">Getting location…</span>
        </div>
        <form id="eveningForm" method="POST">
          <div class="row g-3 mb-3">
            <div class="col-md-4">
              <div class="form-field">
                <label>Hits <span>*</span></label>
                <textarea name="hits" class="field-control" rows="3" required placeholder="Achievements…"></textarea>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-field">
                <label>Missed</label>
                <textarea name="missed" class="field-control" rows="3" placeholder="Challenges…"></textarea>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-field">
                <label>Carry Forward</label>
                <textarea name="carry_forward" class="field-control" rows="3" placeholder="Tomorrow…"></textarea>
              </div>
            </div>
          </div>
          <div class="form-field">
            <label>Daily Summary <span>*</span></label>
            <textarea name="daily_summary" class="field-control" rows="3" required placeholder="Summary of your day…"></textarea>
          </div>
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button type="button" class="btn-c btn-outline-c" id="captureLocBtn" onclick="capLoc()"><i class="fas fa-location-dot"></i> Capture Location</button>
            <button type="button" class="btn-c btn-primary-c" id="subEve" disabled onclick="submitEve()"><i class="fas fa-paper-plane"></i> Submit Evening</button>
          </div>
          <input type="hidden" name="action" value="evening">
          <input type="hidden" name="lat" id="eve_lat">
          <input type="hidden" name="lng" id="eve_lng">
        </form>

      <?php else: ?>
        <!-- EDIT OWN -->
        <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px">
          <div style="display:flex;align-items:center;gap:8px;color:var(--green)">
            <i class="fas fa-circle-check"></i> <strong>Submitted</strong>
            <span class="pill <?= ($own['approval_status']??'')==='Approved'?'pill-appr':(($own['approval_status']??'')==='Rejected'?'pill-reje':'pill-pend') ?>"><?= h($own['approval_status']??'Pending') ?></span>
          </div>
          <button class="btn-c btn-outline-c btn-sm-c" data-bs-toggle="collapse" data-bs-target="#editOwn">
            <i class="fas fa-pen"></i> Edit Report
          </button>
        </div>
        <div class="collapse mt-3" id="editOwn">
          <form method="POST">
            <input type="hidden" name="action" value="edit_own">
            <input type="hidden" name="report_date" value="<?= $today ?>">
            <div class="row g-3 mb-3">
              <div class="col-12">
                <div class="form-field">
                  <label>Morning Plan</label>
                  <textarea name="morning" class="field-control" rows="3"><?= h($own['Morning']??'') ?></textarea>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-field"><label>Hits</label><textarea name="hits" class="field-control" rows="3"><?= h($own['Hits']??'') ?></textarea></div>
              </div>
              <div class="col-md-4">
                <div class="form-field"><label>Missed</label><textarea name="missed" class="field-control" rows="3"><?= h($own['Missed']??'') ?></textarea></div>
              </div>
              <div class="col-md-4">
                <div class="form-field"><label>Carry Forward</label><textarea name="carry_forward" class="field-control" rows="3"><?= h($own['carry forward']??'') ?></textarea></div>
              </div>
              <div class="col-12">
                <div class="form-field"><label>Daily Summary</label><textarea name="daily_summary" class="field-control" rows="3"><?= h($own['daily_summary']??'') ?></textarea></div>
              </div>
              <div class="col-md-6">
                <div class="form-field">
                  <label>Location Type</label>
                  <select name="location_type" class="field-control">
                    <?php foreach([''=>'— Select —','Office'=>'Office','Client Visit'=>'Client Visit','Field Work'=>'Field Work','Work From Home'=>'Work From Home'] as $val=>$lbl): ?>
                    <option value="<?=$val?>" <?= ($own['location_type']??'')===$val?'selected':'' ?>><?=$lbl?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-field"><label>Client Name</label><input type="text" name="client_name" class="field-control" value="<?= h($own['client_name']??'') ?>"></div>
              </div>
            </div>
            <button type="submit" class="btn-c btn-primary-c"><i class="fas fa-floppy-disk"></i> Save Changes</button>
          </form>
        </div>
      <?php endif; ?>
      </div>
    </div>

    <!-- ─── MY REPORT HISTORY (NEW) ─── -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-user-clock"></i> My Report History</div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <span class="badge-custom badge-info"><?= count($my_reports) ?> record<?= count($my_reports)===1?'':'s' ?></span>
          <button class="btn-c btn-primary-c btn-sm-c" data-bs-toggle="modal" data-bs-target="#addOwnModal">
            <i class="fas fa-plus"></i> Add Entry
          </button>
        </div>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($my_reports)): ?>
          <div style="text-align:center;padding:32px 20px;color:var(--muted)">
            <i class="fas fa-clipboard-list" style="font-size:2.2rem;opacity:.3;display:block;margin-bottom:10px"></i>
            <p style="font-size:13px">No entries yet for the selected date range. Use "Add Entry" to log one.</p>
          </div>
        <?php else: ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Date</th><th>Morning</th><th>Hits</th><th>Missed</th><th>Carry</th><th>Summary</th><th>Status</th><th>Remark</th><th>Location</th><th>Client</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($my_reports as $r):
              $mst = $r['approval_status'] ?? 'Pending';
              $mpc = $mst==='Approved'?'pill-appr':($mst==='Rejected'?'pill-reje':'pill-pend');
              $mmid = 'myr_'.str_replace('-','_',$r['report_date']);
              $mlocked = $mst === 'Approved';
            ?>
              <tr>
                <td class="mono" style="white-space:nowrap"><?= date('d M Y',strtotime($r['report_date'])) ?></td>
                <?php foreach(['Morning','Hits','Missed','carry forward','daily_summary'] as $col): ?>
                <td><span class="trunc" title="<?= h($r[$col]??'') ?>"><?= h($r[$col]??'—') ?></span></td>
                <?php endforeach; ?>
                <td><span class="pill <?=$mpc?>"><?=$mst?></span></td>
                <td><span class="trunc" title="<?= h($r['manager_remark']??'') ?>"><?= h($r['manager_remark']??'—') ?></span></td>
                <td><?= $r['location_type']?'<span class="badge-custom badge-info">'.h($r['location_type']).'</span>':'—' ?></td>
                <td style="font-size:11px"><?= h($r['client_name']??'—') ?></td>
                <td>
                  <?php if ($mlocked): ?>
                    <span class="badge-custom badge-success"><i class="fas fa-lock"></i> Locked</span>
                  <?php else: ?>
                    <button class="btn-c btn-outline-c btn-xs-c" data-bs-toggle="modal" data-bs-target="#<?=$mmid?>"><i class="fas fa-pen"></i> Edit</button>
                  <?php endif; ?>
                </td>
              </tr>

              <?php if (!$mlocked): ?>
              <!-- Edit Own-History Modal -->
              <div class="modal fade" id="<?=$mmid?>" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered modal-lg">
                  <div class="modal-content" style="border-radius:var(--radius);border:none">
                    <div class="modal-header" style="background:linear-gradient(135deg,var(--sidebar-bg),#1e3a8a);border:none">
                      <h5 class="modal-title" style="color:#fff;font-weight:700;font-size:14px">
                        <i class="fas fa-pen me-2" style="color:#a5b4fc"></i>Edit My Report
                        <small style="color:rgba(255,255,255,.6);font-weight:400"> <?= date('d M Y',strtotime($r['report_date'])) ?></small>
                      </h5>
                      <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body p-4">
                      <form method="POST">
                        <input type="hidden" name="action" value="save_own_report">
                        <input type="hidden" name="report_date" value="<?= h($r['report_date']) ?>">
                        <div class="row g-3">
                          <div class="col-12">
                            <div class="form-field"><label>Morning Plan</label><textarea name="morning" class="field-control" rows="2"><?= h($r['Morning']??'') ?></textarea></div>
                          </div>
                          <div class="col-md-4">
                            <div class="form-field"><label>Hits</label><textarea name="hits" class="field-control" rows="2"><?= h($r['Hits']??'') ?></textarea></div>
                          </div>
                          <div class="col-md-4">
                            <div class="form-field"><label>Missed</label><textarea name="missed" class="field-control" rows="2"><?= h($r['Missed']??'') ?></textarea></div>
                          </div>
                          <div class="col-md-4">
                            <div class="form-field"><label>Carry Forward</label><textarea name="carry_forward" class="field-control" rows="2"><?= h($r['carry forward']??'') ?></textarea></div>
                          </div>
                          <div class="col-12">
                            <div class="form-field"><label>Daily Summary</label><textarea name="daily_summary" class="field-control" rows="2"><?= h($r['daily_summary']??'') ?></textarea></div>
                          </div>
                          <div class="col-md-6">
                            <div class="form-field">
                              <label>Location Type</label>
                              <select name="location_type" class="field-control">
                                <?php foreach([''=>'— Select —','Office'=>'Office','Client Visit'=>'Client Visit','Field Work'=>'Field Work','Work From Home'=>'Work From Home'] as $val=>$lbl): ?>
                                <option value="<?=$val?>" <?= ($r['location_type']??'')===$val?'selected':'' ?>><?=$lbl?></option>
                                <?php endforeach; ?>
                              </select>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <div class="form-field"><label>Client Name</label><input type="text" name="client_name" class="field-control" value="<?= h($r['client_name']??'') ?>"></div>
                          </div>
                        </div>
                        <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:8px">
                          <button type="button" class="btn-c btn-outline-c" data-bs-dismiss="modal">Cancel</button>
                          <button type="submit" class="btn-c btn-primary-c"><i class="fas fa-floppy-disk"></i> Save</button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
              <?php endif; ?>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Add Own-History Modal -->
    <div class="modal fade" id="addOwnModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content" style="border-radius:var(--radius);border:none">
          <div class="modal-header" style="background:linear-gradient(135deg,var(--sidebar-bg),#1e3a8a);border:none">
            <h5 class="modal-title" style="color:#fff;font-weight:700;font-size:14px">
              <i class="fas fa-plus me-2" style="color:#a5b4fc"></i>Add Report Entry
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body p-4">
            <form method="POST">
              <input type="hidden" name="action" value="save_own_report">
              <div class="row g-3">
                <div class="col-md-6">
                  <div class="form-field">
                    <label>Report Date <span>*</span></label>
                    <input type="date" name="report_date" class="field-control" max="<?= $today ?>" value="<?= $today ?>" required>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-field">
                    <label>Location Type</label>
                    <select name="location_type" class="field-control">
                      <option value="">— Select —</option>
                      <option>Office</option><option>Client Visit</option>
                      <option>Field Work</option><option>Work From Home</option>
                    </select>
                  </div>
                </div>
                <div class="col-12">
                  <div class="form-field"><label>Morning Plan</label><textarea name="morning" class="field-control" rows="2" placeholder="Plan for the day…"></textarea></div>
                </div>
                <div class="col-md-4">
                  <div class="form-field"><label>Hits</label><textarea name="hits" class="field-control" rows="2" placeholder="Achievements…"></textarea></div>
                </div>
                <div class="col-md-4">
                  <div class="form-field"><label>Missed</label><textarea name="missed" class="field-control" rows="2" placeholder="Challenges…"></textarea></div>
                </div>
                <div class="col-md-4">
                  <div class="form-field"><label>Carry Forward</label><textarea name="carry_forward" class="field-control" rows="2" placeholder="Tomorrow…"></textarea></div>
                </div>
                <div class="col-12">
                  <div class="form-field"><label>Daily Summary</label><textarea name="daily_summary" class="field-control" rows="2" placeholder="Summary…"></textarea></div>
                </div>
                <div class="col-12">
                  <div class="form-field"><label>Client Name</label><input type="text" name="client_name" class="field-control" placeholder="If applicable"></div>
                </div>
              </div>
              <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:8px">
                <button type="button" class="btn-c btn-outline-c" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn-c btn-primary-c"><i class="fas fa-floppy-disk"></i> Save Entry</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- ─── PENDING TEAM APPROVALS ─── -->
    <?php if (!empty($pending)): ?>
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-hourglass-half"></i> Team Pending Approvals</div>
        <span class="badge-custom badge-warning"><?= count($pending) ?> pending</span>
      </div>
      <div class="dash-card-body" style="padding:0">
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Date</th><th>Employee</th><th>Morning</th><th>Hits</th><th>Missed</th><th>Carry</th><th>Summary</th><th>Location</th><th>Client</th><th>Login</th><th>Logout</th><th>Photo</th><th>Map In</th><th>Map Out</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($pending as $r):
              $mid='pm_'.$r['user_id'].'_'.str_replace('-','_',$r['report_date']);
            ?>
              <tr>
                <td class="mono"><?= date('d M Y',strtotime($r['report_date'])) ?></td>
                <td><div style="display:flex;align-items:center;gap:8px"><div class="emp-av"><?= strtoupper(substr($r['ename']??'?',0,1)) ?></div><strong style="font-size:12px"><?= h($r['ename']??'-') ?></strong></div></td>
                <?php foreach(['Morning','Hits','Missed','carry forward','daily_summary'] as $col): ?>
                <td><span class="trunc" title="<?= h($r[$col]??'') ?>"><?= h($r[$col]??'—') ?></span></td>
                <?php endforeach; ?>
                <td><?= $r['location_type']?'<span class="badge-custom badge-info">'.h($r['location_type']).'</span>':'—' ?></td>
                <td style="font-size:11px"><?= h($r['client_name']??'—') ?></td>
                <td class="mono"><?= $r['login_time']?date('H:i',strtotime($r['login_time'])):'—' ?></td>
                <td class="mono"><?= $r['logout_time']?date('H:i',strtotime($r['logout_time'])):'—' ?></td>
                <td><?= !empty($r['photo_path'])?'<a href="'.h($r['photo_path']).'" target="_blank" class="map-lnk"><i class="fas fa-image"></i></a>':'—' ?></td>
                <td><?= !empty($r['latitude'])?'<a href="https://www.google.com/maps?q='.$r['latitude'].','.$r['longitude'].'" target="_blank" class="map-lnk"><i class="fas fa-location-dot"></i> In</a>':'—' ?></td>
                <td><?= !empty($r['logout_latitude'])?'<a href="https://www.google.com/maps?q='.$r['logout_latitude'].','.$r['logout_longitude'].'" target="_blank" class="map-lnk"><i class="fas fa-location-dot"></i> Out</a>':'—' ?></td>
                <td><button class="btn-c btn-primary-c btn-xs-c" data-bs-toggle="modal" data-bs-target="#<?=$mid?>"><i class="fas fa-gavel"></i> Review</button></td>
              </tr>

              <!-- Review Modal -->
              <div class="modal fade" id="<?=$mid?>" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered modal-lg">
                  <div class="modal-content" style="border-radius:var(--radius);border:none">
                    <div class="modal-header" style="background:linear-gradient(135deg,var(--sidebar-bg),#1e3a8a);border:none">
                      <h5 class="modal-title" style="color:#fff;font-weight:700;font-size:14px">
                        <i class="fas fa-gavel me-2" style="color:#a5b4fc"></i>Review – <?= h($r['ename']??'') ?>
                        <small style="color:rgba(255,255,255,.6);font-weight:400"> <?= date('d M Y',strtotime($r['report_date'])) ?></small>
                      </h5>
                      <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body p-4">
                      <div class="row g-2 mb-3">
                        <div class="col-12">
                          <div style="background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:12px">
                            <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Morning Plan</div>
                            <div style="font-size:13px;color:var(--ink-2)"><?= nl2br(h($r['Morning']??'—')) ?></div>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div style="background:#d1fae5;border:1px solid #a7f3d0;border-radius:var(--radius-sm);padding:12px">
                            <div style="font-size:11px;font-weight:700;color:#065f46;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Hits</div>
                            <div style="font-size:12.5px"><?= nl2br(h($r['Hits']??'—')) ?></div>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div style="background:#fef3c7;border:1px solid #fde68a;border-radius:var(--radius-sm);padding:12px">
                            <div style="font-size:11px;font-weight:700;color:#92400e;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Missed</div>
                            <div style="font-size:12.5px"><?= nl2br(h($r['Missed']??'—')) ?></div>
                          </div>
                        </div>
                        <div class="col-md-4">
                          <div style="background:#dbeafe;border:1px solid #bfdbfe;border-radius:var(--radius-sm);padding:12px">
                            <div style="font-size:11px;font-weight:700;color:#1e40af;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Carry Forward</div>
                            <div style="font-size:12.5px"><?= nl2br(h($r['carry forward']??'—')) ?></div>
                          </div>
                        </div>
                        <div class="col-12">
                          <div style="background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:12px">
                            <div style="font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px">Summary</div>
                            <div style="font-size:13px;color:var(--ink-2)"><?= nl2br(h($r['daily_summary']??'—')) ?></div>
                          </div>
                        </div>
                        <?php if (!empty($r['photo_path']) || !empty($r['latitude']) || !empty($r['logout_latitude'])): ?>
                        <div class="col-12">
                          <div style="display:flex;gap:8px;flex-wrap:wrap">
                            <?php if(!empty($r['photo_path'])): ?><a href="<?= h($r['photo_path']) ?>" target="_blank" class="btn-c btn-outline-c btn-sm-c"><i class="fas fa-image"></i> View Selfie</a><?php endif; ?>
                            <?php if(!empty($r['latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['latitude'] ?>,<?= $r['longitude'] ?>" target="_blank" class="btn-c btn-outline-c btn-sm-c"><i class="fas fa-map-pin"></i> Login Map</a><?php endif; ?>
                            <?php if(!empty($r['logout_latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['logout_latitude'] ?>,<?= $r['logout_longitude'] ?>" target="_blank" class="btn-c btn-outline-c btn-sm-c"><i class="fas fa-map-marker-alt"></i> Logout Map</a><?php endif; ?>
                          </div>
                        </div>
                        <?php endif; ?>
                      </div>
                      <form method="POST">
                        <input type="hidden" name="action" value="approve_report">
                        <input type="hidden" name="report_user_id" value="<?=$r['user_id']?>">
                        <input type="hidden" name="report_date" value="<?=$r['report_date']?>">
                        <div class="row g-2">
                          <div class="col-md-5">
                            <div class="form-field">
                              <label>Decision <span style="color:var(--red)">*</span></label>
                              <select name="new_status" class="field-control" required>
                                <option value="">Select…</option>
                                <option value="Approved">✅ Approve</option>
                                <option value="Rejected">❌ Reject</option>
                              </select>
                            </div>
                          </div>
                          <div class="col-md-7">
                            <div class="form-field">
                              <label>Remark</label>
                              <textarea name="manager_remark" class="field-control" rows="2" placeholder="Optional comment…"></textarea>
                            </div>
                          </div>
                        </div>
                        <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:4px">
                          <button type="button" class="btn-c btn-outline-c" data-bs-dismiss="modal">Cancel</button>
                          <button type="submit" class="btn-c btn-primary-c"><i class="fas fa-paper-plane"></i> Submit</button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- ─── HISTORY ─── -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-clock-rotate-left"></i> All Reports History</div>
        <a href="?export=excel&view=<?=urlencode($view)?>&from=<?=urlencode($from)?>&to=<?=urlencode($to)?>&employee=<?=urlencode($emp_f)?>&status=<?=urlencode($st_f)?>"
           class="btn-c btn-success-c btn-sm-c">
          <i class="fas fa-file-excel"></i> Export Excel
        </a>
      </div>
      <div class="dash-card-body">
        <!-- Filter Row -->
        <form method="get" class="row g-2 mb-3">
          <div class="col-md-2 col-6">
            <select name="view" class="field-control" style="font-size:12px;padding:7px 10px">
              <option value="today" <?=$view==='today'?'selected':''?>>Today</option>
              <option value="week"  <?=$view==='week'?'selected':''?>>This Week</option>
              <option value="month" <?=$view==='month'?'selected':''?>>This Month</option>
            </select>
          </div>
          <div class="col-md-2 col-6"><input type="date" name="from" class="field-control" style="font-size:12px;padding:7px 10px" value="<?= h($from) ?>"></div>
          <div class="col-md-2 col-6"><input type="date" name="to" class="field-control" style="font-size:12px;padding:7px 10px" value="<?= h($to) ?>"></div>
          <div class="col-md-2 col-6">
            <select name="employee" class="field-control" style="font-size:12px;padding:7px 10px">
              <option value="">All Employees</option>
              <?php foreach($all_emp as $e): ?>
              <option value="<?=$e['id']?>" <?=$emp_f==$e['id']?'selected':''?>><?= h($e['username']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2 col-6">
            <select name="status" class="field-control" style="font-size:12px;padding:7px 10px">
              <option value="">All Status</option>
              <option value="Pending"  <?=$st_f==='Pending'?'selected':''?>>Pending</option>
              <option value="Approved" <?=$st_f==='Approved'?'selected':''?>>Approved</option>
              <option value="Rejected" <?=$st_f==='Rejected'?'selected':''?>>Rejected</option>
            </select>
          </div>
          <div class="col-md-2 col-6 d-flex gap-1">
            <button type="submit" class="btn-c btn-primary-c btn-sm-c flex-fill"><i class="fas fa-filter"></i> Filter</button>
            <a href="manager_daily_report.php" class="btn-c btn-outline-c btn-sm-c"><i class="fas fa-times"></i></a>
          </div>
        </form>
        <p style="font-size:11px;color:var(--muted);margin:-6px 0 12px">
          <i class="fas fa-circle-info"></i> This filter (date range &amp; status) also applies to "My Report History" above.
        </p>

        <?php if (empty($reports)): ?>
          <div style="text-align:center;padding:40px 20px;color:var(--muted)">
            <i class="fas fa-inbox" style="font-size:2.5rem;opacity:.3;display:block;margin-bottom:12px"></i>
            <p style="font-size:13px">No records found for the selected filters.</p>
          </div>
        <?php else: ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr><th>Date</th><th>Employee</th><th>Morning</th><th>Hits</th><th>Missed</th><th>Carry</th><th>Summary</th><th>Status</th><th>Remark</th><th>Location</th><th>Client</th><th>Login</th><th>Logout</th><th>Photo</th><th>Map In</th><th>Map Out</th></tr></thead>
            <tbody>
            <?php foreach ($reports as $r):
              $st=$r['approval_status']??'Pending';
              $pc=$st==='Approved'?'pill-appr':($st==='Rejected'?'pill-reje':'pill-pend');
            ?>
              <tr>
                <td class="mono" style="white-space:nowrap"><?= date('d M Y',strtotime($r['report_date'])) ?></td>
                <td><div style="display:flex;align-items:center;gap:8px"><div class="emp-av"><?= strtoupper(substr($r['ename']??'?',0,1)) ?></div><strong style="font-size:12px"><?= h($r['ename']??$r['user_id']) ?></strong></div></td>
                <?php foreach(['Morning','Hits','Missed','carry forward','daily_summary'] as $col): ?>
                <td><span class="trunc" title="<?= h($r[$col]??'') ?>"><?= h($r[$col]??'—') ?></span></td>
                <?php endforeach; ?>
                <td><span class="pill <?=$pc?>"><?=$st?></span></td>
                <td><span class="trunc" title="<?= h($r['manager_remark']??'') ?>"><?= h($r['manager_remark']??'—') ?></span></td>
                <td><?= $r['location_type']?'<span class="badge-custom badge-info">'.h($r['location_type']).'</span>':'—' ?></td>
                <td style="font-size:11px"><?= h($r['client_name']??'—') ?></td>
                <td class="mono"><?= $r['login_time']?date('H:i',strtotime($r['login_time'])):'—' ?></td>
                <td class="mono"><?= $r['logout_time']?date('H:i',strtotime($r['logout_time'])):'—' ?></td>
                <td><?= !empty($r['photo_path'])?'<a href="'.h($r['photo_path']).'" target="_blank" class="map-lnk"><i class="fas fa-image"></i></a>':'—' ?></td>
                <td><?= !empty($r['latitude'])?'<a href="https://www.google.com/maps?q='.$r['latitude'].','.$r['longitude'].'" target="_blank" class="map-lnk"><i class="fas fa-location-dot"></i></a>':'—' ?></td>
                <td><?= !empty($r['logout_latitude'])?'<a href="https://www.google.com/maps?q='.$r['logout_latitude'].','.$r['logout_longitude'].'" target="_blank" class="map-lnk"><i class="fas fa-location-dot"></i></a>':'—' ?></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>

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

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (!sb || !ov) return;
  const isOpen = sb.classList.contains('open');
  sb.classList.toggle('open', !isOpen);
  ov.classList.toggle('active', !isOpen);
}
function closeSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (sb) sb.classList.remove('open');
  if (ov) ov.classList.remove('active');
}
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeSidebar();
});
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('#sidebar .nav-link').forEach(function(a) {
    a.addEventListener('click', function() {
      if (window.innerWidth <= 768) closeSidebar();
    });
  });
});

function showErr(id,msgId,msg,type) {
  var el=document.getElementById(id), ml=document.getElementById(msgId);
  if(!el||!ml) return;
  ml.textContent=msg;
  el.className='inline-error show'+(type?' '+type:'');
  el.scrollIntoView({behavior:'smooth',block:'nearest'});
  setTimeout(function(){el.classList.remove('show');},7000);
}
function hideErr(id){var el=document.getElementById(id); if(el) el.classList.remove('show');}

/* ══════════════════════════════════════════════
   CAMERA — robust start with visible error/retry option
   so the "attendance option" never gets silently stuck.
══════════════════════════════════════════════ */
var video         = document.getElementById('video');
var canvas        = document.getElementById('canvas');
var preview       = document.getElementById('preview');
var capBtn        = document.getElementById('capBtn');
var retakeBtn     = document.getElementById('retakeBtn');
var subMornBtn    = document.getElementById('subMorn');
var cameraWrap    = document.getElementById('cameraWrap');
var cameraLoading = document.getElementById('cameraLoading');
var cameraOverlay = document.getElementById('cameraOverlay');
var cameraErrBox  = document.getElementById('cameraErrorBox');
var cameraErrMsg  = document.getElementById('cameraErrorMsg');
var photoData     = '';
var cameraReady   = false;

function showCameraError(msg){
  if(cameraLoading) cameraLoading.style.display='none';
  if(video) video.style.display='none';
  if(cameraOverlay) cameraOverlay.style.display='none';
  if(cameraWrap) cameraWrap.style.minHeight='0';
  if(cameraErrMsg) cameraErrMsg.textContent = msg || 'Camera could not start. Tap to retry.';
  if(cameraErrBox) cameraErrBox.classList.add('show');
  if(capBtn){ capBtn.disabled=true; capBtn.style.display='none'; }
}

if (video) {
  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 startCam(){
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
      showCameraError('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]);
        video.srcObject = stream;
        try{ await video.play(); }catch(e){}
        cameraReady=true;
        if(cameraLoading) cameraLoading.style.display='none';
        video.style.display='block';
        if(cameraOverlay) cameraOverlay.style.display='block';
        if(capBtn) capBtn.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(!cameraReady && lastErr){
      var n=lastErr.name||'';
      if(n==='NotAllowedError'||n==='PermissionDeniedError'){
        showCameraError('Camera permission denied. Please allow camera access in your browser/app settings, then reopen this page.');
      }else if(n==='NotFoundError'||n==='DevicesNotFoundError'){
        showCameraError('No camera found on this device.');
      }else if(n==='NotReadableError'||n==='TrackStartError'||n==='AbortError'){
        showCameraError('Camera is busy. Close other apps using the camera, then tap Retry.');
      }else if(n==='SecurityError'){
        showCameraError('Camera blocked by security policy. Ensure the page is using HTTPS.');
      }else{
        showCameraError('Camera error: '+(lastErr.message||n)+'. Tap Retry.');
      }
    }
  })();
}

function capPhoto() {
  if(!cameraReady || !video){ showErr('morningError','morningErrorMsg','Camera not ready. Please tap Retry.','warning'); return; }
  if(!video.videoWidth || !video.videoHeight){ showErr('morningError','morningErrorMsg','Camera feed not active yet. Wait a moment.','warning'); return; }
  canvas.width=video.videoWidth; canvas.height=video.videoHeight;
  canvas.getContext('2d').drawImage(video,0,0);
  photoData=canvas.toDataURL('image/jpeg',.85);
  preview.src=photoData; preview.style.display='block'; video.style.display='none';
  if(cameraOverlay) cameraOverlay.style.display='none';
  capBtn.style.display='none';
  retakeBtn.style.display='';
  subMornBtn.style.display='';
  hideErr('morningError');
}
function retake() {
  photoData=''; preview.style.display='none'; video.style.display='block';
  if(cameraOverlay) cameraOverlay.style.display='block';
  capBtn.style.display='';
  retakeBtn.style.display='none';
  subMornBtn.style.display='none';
}

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

/* ══════════════════════════════════════════════
   LOCATION — explicit capture button + status bar + retry
══════════════════════════════════════════════ */
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 submitMorn() {
  if (!photoData) { showErr('morningError','morningErrorMsg','Capture selfie first.','warning'); return; }
  if (!document.getElementById('loc_type').value) { showErr('morningError','morningErrorMsg','Select location type.','warning'); return; }
  if (document.getElementById('loc_type').value === 'Client Visit' && !document.getElementById('cli_name').value.trim()) { showErr('morningError','morningErrorMsg','Enter the client name.','warning'); return; }
  if (!document.getElementById('morning_txt').value.trim()) { showErr('morningError','morningErrorMsg','Enter morning plan.','warning'); return; }

  hideErr('morningError');
  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='Submitting…';
  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','morning'); add('lat',lat); add('lng',lng);
  add('photo_data',photoData); add('location_type',document.getElementById('loc_type').value);
  add('client_name',document.getElementById('cli_name')?.value||'');
  add('morning',document.getElementById('morning_txt').value);
  document.body.appendChild(f); f.submit();
}

var eveLoc=false;
async function capLoc() {
  var btn=document.getElementById('captureLocBtn');
  var locStatus=document.getElementById('locStatus');
  var locStatusMsg=document.getElementById('locStatusMsg');

  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();
    document.getElementById('eve_lat').value=l.lat;
    document.getElementById('eve_lng').value=l.lng;
    eveLoc=true; document.getElementById('subEve').disabled=false;
    if(btn){ btn.innerHTML='<i class="fas fa-check-circle"></i> Location Captured'; btn.classList.remove('btn-outline-c'); btn.classList.add('btn-success-c'); 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.'; }
    eveLoc=false;
  }
}
function submitEve() {
  var hits=document.querySelector('#eveningForm [name="hits"]');
  if(hits && !hits.value.trim()){ showErr('eveningError','eveningErrorMsg','Please fill in the Hits field.','warning'); return; }
  if (!eveLoc) { showErr('eveningError','eveningErrorMsg','Capture location first.','warning'); return; }
  hideErr('eveningError');
  document.getElementById('loadingText').textContent='Submitting evening report…';
  document.getElementById('loadingOverlay').classList.add('show');
  document.getElementById('eveningForm').submit();
}
</script>
</body>
</html>