<?php
session_start();

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

include 'config.php';
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['employee', 'manager'])) {
    header("Location: index.php");
    exit();
}
$user_id  = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'User';
$role     = $_SESSION['role'];
$today    = date('Y-m-d');
$message  = '';
$message_type = '';

function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

/* ── MANAGER APPROVAL ── */
if ($role === 'manager' && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'approve_report') {
    $report_user_id = $_POST['report_user_id'] ?? '';
    $report_date    = $_POST['report_date'] ?? '';
    $new_status     = $_POST['new_status'] ?? '';
    $manager_remark = $_POST['manager_remark'] ?? '';
    if ($new_status === 'Approved' || $new_status === 'Rejected') {
        $stmt = $conn->prepare("UPDATE daily_reports SET approval_status=?, manager_remark=? WHERE user_id=? AND report_date=?");
        $stmt->bind_param("ssss", $new_status, $manager_remark, $report_user_id, $report_date);
        $stmt->execute(); $stmt->close();
        $message = "Report updated successfully."; $message_type = 'success';
    } else { $message = "Invalid status."; $message_type = 'danger'; }
}

/* ── TODAY REPORT (EMPLOYEE) ── */
$today_report = []; $morning_submitted = false;
$evening_submitted = false; $locked = false; $status = 'Pending';
if ($role === 'employee') {
    $stmt = $conn->prepare("SELECT * FROM daily_reports WHERE user_id=? AND report_date=?");
    $stmt->bind_param("ss", $user_id, $today);
    $stmt->execute();
    $today_report      = $stmt->get_result()->fetch_assoc() ?? [];
    $stmt->close();
    $morning_submitted = !empty($today_report['Morning']) || !empty($today_report['login_time'] ?? '');
    $evening_submitted = !empty($today_report['logout_time'] ?? '');
    $status            = $today_report['approval_status'] ?? 'Pending';
    $locked            = ($status == 'Approved');
}

/* ── EMPLOYEE SUBMIT ── */
if ($role === 'employee' && $_SERVER['REQUEST_METHOD'] == 'POST' && !$locked) {
    $action     = $_POST['action'] ?? '';
    $lat        = $_POST['lat'] ?? null;
    $lng        = $_POST['lng'] ?? null;
    $photo_path = '';

    if ($action === 'morning') {
        $morning       = $_POST['morning'] ?? '';
        $location_type = $_POST['location_type'] ?? '';
        $client_name   = $_POST['client_name'] ?? '';
        if (empty($_POST['photo_data'])) {
            $message = "Selfie photo is required."; $message_type = 'warning';
        } else {
            $upload_dir = 'uploads/attendance/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $photo_data = str_replace(['data:image/jpeg;base64,', ' '], ['', '+'], $_POST['photo_data']);
            $data       = base64_decode($photo_data);
            $photo_name = $user_id . '_morning_' . date('Ymd_His') . '.jpg';
            $photo_path = $upload_dir . $photo_name;
            if (file_put_contents($photo_path, $data) === false) { $message = "Failed to save photo."; $message_type = 'danger'; }
        }
        if (empty($message)) {
            if (!$morning_submitted) {
                /*
                 * IMPORTANT FIX:
                 * `Location` and `Name of the Client` are NOT NULL columns
                 * with no default in the daily_reports table. The old query
                 * never supplied them (it only set location_type/client_name,
                 * which are separate columns), so MySQL rejected the insert
                 * under strict mode and mysqli threw an uncaught exception
                 * -> HTTP 500. We now map location_type -> Location enum and
                 * pass 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[$location_type] ?? 'Corporate Office';
                $name_of_client = ($client_name !== '') ? $client_name : 'N/A';

                $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 (?,?,?,?,?,?,?,?,?,?,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'
                ");
                if (!$stmt) {
                    $message = "Database error: " . $conn->error;
                    $message_type = 'danger';
                } else {
                    $stmt->bind_param(
                        "sssssssdds",
                        $user_id, $today, $location_enum, $name_of_client, $morning,
                        $location_type, $client_name, $lat, $lng, $photo_path
                    );
                    if (!$stmt->execute()) {
                        $message = "Failed to save report: " . $stmt->error;
                        $message_type = 'danger';
                        $stmt->close();
                    } else {
                        $stmt->close();
                        header("Location: daily_report.php"); exit();
                    }
                }
            }
        }
    } elseif ($action === 'evening') {
        $hits    = $_POST['hits'] ?? ''; $missed = $_POST['missed'] ?? '';
        $carry   = $_POST['carry_forward'] ?? ''; $summary = $_POST['daily_summary'] ?? '';
        $stmt = $conn->prepare("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=?");
        $stmt->bind_param("ssssddss", $hits, $missed, $carry, $summary, $lat, $lng, $user_id, $today);
        $stmt->execute(); $stmt->close();
        header("Location: daily_report.php"); exit();
    }
}

/* ── FILTER ── */
$view = $_GET['view'] ?? 'month';
$from = $_GET['from'] ?? ''; $to = $_GET['to'] ?? '';
if (!empty($from) && !empty($to)) { $start = $from; $end = $to; }
elseif ($view == 'today') { $start = $today; $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'])) {
    if ($role === 'employee') {
        $stmt = $conn->prepare("SELECT dr.*, u.username AS employee_name FROM daily_reports dr LEFT JOIN users u ON dr.user_id=u.id WHERE dr.user_id=? AND report_date BETWEEN ? AND ? ORDER BY report_date DESC");
        $stmt->bind_param("sss", $user_id, $start, $end);
    } else {
        $stmt = $conn->prepare("SELECT dr.*, u.username AS employee_name FROM daily_reports dr LEFT JOIN users u ON dr.user_id=u.id WHERE report_date BETWEEN ? AND ? ORDER BY report_date DESC");
        $stmt->bind_param("ss", $start, $end);
    }
    $stmt->execute(); $res = $stmt->get_result();
    if ($_GET['export'] == 'excel') {
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=reports.xls");
        echo "Date\tEmployee\tMorning\tHits\tMissed\tCarry\tSummary\tStatus\tManager Comment\tLocation\tClient\tLogin\tLogout\n";
        while ($r = $res->fetch_assoc()) echo implode("\t", [$r['report_date']??'',$r['employee_name']??'',$r['Morning']??'',$r['Hits']??'',$r['Missed']??'',$r['carry forward']??'',$r['daily_summary']??'',$r['approval_status']??'',$r['manager_remark']??'',$r['location_type']??'',$r['client_name']??'',$r['login_time']??'',$r['logout_time']??''])."\n";
        exit;
    }
    if ($_GET['export'] == 'pdf') {
        require('fpdf/fpdf.php');
        $pdf = new FPDF('L','mm','A4'); $pdf->AddPage(); $pdf->SetFont('Arial','B',7);
        foreach(['Date','Employee','Morning','Hits','Missed','Carry','Summary','Status','Manager','Location','Client','Login','Logout'] as $col) $pdf->Cell(22,8,$col,1);
        $pdf->Ln(); $pdf->SetFont('Arial','',6);
        while ($r = $res->fetch_assoc()) {
            foreach([$r['report_date']??'',substr($r['employee_name']??'',0,12),substr($r['Morning']??'',0,12),$r['Hits']??'',$r['Missed']??'',$r['carry forward']??'',substr($r['daily_summary']??'',0,10),$r['approval_status']??'',substr($r['manager_remark']??'',0,10),$r['location_type']??'',$r['client_name']??'',substr($r['login_time']??'',0,10),substr($r['logout_time']??'',0,10)] as $v) $pdf->Cell(22,8,$v,1);
            $pdf->Ln();
        }
        $pdf->Output('D','reports.pdf'); exit;
    }
}

/* ── HISTORY ── */
if ($role === 'employee') {
    $stmt = $conn->prepare("SELECT * FROM daily_reports WHERE user_id=? AND report_date BETWEEN ? AND ? ORDER BY report_date DESC");
    $stmt->bind_param("sss", $user_id, $start, $end);
} else {
    $stmt = $conn->prepare("SELECT dr.*, u.username AS employee_name FROM daily_reports dr LEFT JOIN users u ON dr.user_id=u.id WHERE report_date BETWEEN ? AND ? ORDER BY report_date DESC");
    $stmt->bind_param("ss", $start, $end);
}
$stmt->execute(); $reports = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close();

/* ── PENDING (MANAGER) ── */
$pending_reports = [];
if ($role === 'manager') {
    $stmt = $conn->prepare("SELECT dr.*, u.username AS employee_name FROM daily_reports dr LEFT JOIN users u ON dr.user_id=u.id WHERE approval_status='Pending' ORDER BY report_date DESC");
    $stmt->execute(); $pending_reports = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close();
}
?>
<!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 · Daily Report & Attendance</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&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#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);
  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;transform:translateX(0);transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.closed{transform:translateX(-100%)}
.sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:200;opacity:0;transition:opacity .3s ease}
.sidebar-overlay.show{display:block;opacity:1}
.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}
.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}
.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}

/* PAGE */
.page{padding:22px;flex:1}
.page-header{margin-bottom:22px;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px}
.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}
.back-btn{display:inline-flex;align-items:center;gap:7px;padding:8px 16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-weight:600;color:var(--ink-2);text-decoration:none;box-shadow:var(--shadow);transition:background .15s}
.back-btn:hover{background:var(--bg);color:var(--ink);text-decoration:none}

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

/* ALERTS */
.alert-custom{padding:12px 16px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:16px;display:flex;align-items:flex-start;gap:10px}
.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 — only for form validation, never for permissions */
.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)}}

/* STATUS INDICATOR */
.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}

/* CAMERA */
.camera-wrap{border-radius:var(--radius);overflow:hidden;background:#1e293b;position:relative;margin-bottom:16px;min-height:220px;display:flex;align-items:center;justify-content:center}
#video{width:100%;max-height:340px;object-fit:cover;display:block;border-radius:var(--radius)}
#canvas{display:none}
#photoPreview{width:100%;border-radius:var(--radius);display:none;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 STATE */
.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:28px;animation:spin .8s linear infinite}

/* CAMERA ERROR STATE — minimal, with retry */
.camera-error-box{display:none;flex-direction:column;align-items:center;justify-content:center;padding:28px 20px;background:#fff7ed;border:2px dashed #fed7aa;border-radius:var(--radius);margin-bottom:16px;text-align:center;gap:8px}
.camera-error-box.show{display:flex}
.camera-error-box i{font-size:32px;color:#f97316}
.camera-error-box p{font-size:13px;color:#7c2d12;line-height:1.6;max-width:280px}

/* FORM */
.form-group{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}
.form-label{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.form-control{width:100%;padding:9px 12px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'DM Sans',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s,background .15s;-webkit-appearance:none}
.form-control:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}
.form-control::placeholder{color:var(--muted)}
select.form-control{cursor:pointer}
textarea.form-control{resize:vertical;min-height:80px;line-height:1.6}
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}

/* BUTTONS */
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:9px 18px;border-radius:var(--radius-sm);font-size:13px;font-weight:700;font-family:'DM Sans',sans-serif;cursor:pointer;border:none;transition:all .15s;text-decoration:none}
.btn-primary{background:linear-gradient(135deg,var(--accent),#6366f1);color:#fff}.btn-primary:hover{opacity:.9;transform:translateY(-1px)}
.btn-success{background:linear-gradient(135deg,var(--green),#10b981);color:#fff}.btn-success:hover{opacity:.9}
.btn-warning{background:linear-gradient(135deg,var(--amber),#f59e0b);color:#fff}
.btn-danger{background:linear-gradient(135deg,var(--red),#ef4444);color:#fff}
.btn-outline{background:var(--surface);border:1.5px solid var(--border);color:var(--ink-2)}.btn-outline:hover{background:var(--bg)}
.btn-block{width:100%}
.btn-lg{padding:12px 22px;font-size:14px}
.btn:disabled{opacity:.45;cursor:not-allowed;transform:none !important}

/* FILTER BAR */
.filter-bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:18px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 18px;box-shadow:var(--shadow)}
.filter-group{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.filter-select{padding:7px 10px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-family:'DM Sans',sans-serif;color:var(--ink-2);background:var(--bg);outline:none;cursor:pointer}
.filter-date{padding:7px 10px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-family:'DM Sans',sans-serif;color:var(--ink-2);background:var(--bg);outline:none}
.filter-spacer{flex:1}
.export-btns{display:flex;gap:8px}

/* TABLE */
.tbl-wrap{overflow-x:auto}
.dash-table{width:100%;border-collapse:collapse;font-size:12px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.6px;padding:10px 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:top}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600;white-space:nowrap}
.badge-success{background:#d1fae5;color:#065f46}
.badge-warning{background:#fef3c7;color:#92400e}
.badge-danger{background:#fee2e2;color:#991b1b}
.badge-purple{background:#ede9fe;color:#5b21b6}
.badge-blue{background:#dbeafe;color:#1e40af}
.map-link,.photo-link{display:inline-flex;align-items:center;gap:4px;color:var(--accent);font-size:11px;font-weight:600;text-decoration:none}
.map-link:hover,.photo-link:hover{text-decoration:underline}
.pending-badge{display:inline-flex;align-items:center;gap:5px;background:#fef3c7;color:#92400e;font-size:11px;font-weight:700;padding:4px 12px;border-radius:20px}
.approve-form select.form-control{font-size:12px;padding:7px 10px;margin-bottom:8px}
.approve-form textarea.form-control{font-size:12px;min-height:55px;margin-bottom:8px}
.empty-state{text-align:center;padding:48px 24px;color:var(--muted)}
.empty-state i{font-size:36px;display:block;margin-bottom:12px;opacity:.35}

/* 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:48px;height:48px;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}

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

@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .content{margin-left:0}
  .page{padding:14px}
  .form-grid{grid-template-columns:1fr}
  .filter-bar{flex-direction:column;align-items:stretch}
  .export-btns{justify-content:flex-end}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay{display:none !important}
  .content{margin-left:var(--sidebar-w)}
}
</style>
</head>
<body>
<div class="layout">

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

<nav class="sidebar closed" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub"><?= $role === 'manager' ? 'Manager' : 'Employee' ?></div>
    </div>
  </div>
  <?php if ($role === 'employee'): ?>
  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_employee.php" class="nav-link"><i class="fas fa-gauge-high"></i> Dashboard</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="apply_leave.php" class="nav-link"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense.php" class="nav-link"><i class="fas fa-receipt"></i> Expenses</a></li>
    <li class="nav-item"><a href="tasks_employee.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="daily_report.php" class="nav-link active"><i class="fas fa-file-lines"></i> Attendance &amp; Daily Report</a></li>
    <li class="nav-item"><a href="employee_grievance.php" class="nav-link"><i class="fas fa-exclamation-triangle"></i> Grievance</a></li>
  </ul>
  <?php else: ?>
  <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"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link active"><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>
  <?php endif; ?>
  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item"><a href="logout.php" class="nav-link danger"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
    </ul>
  </div>
</nav>

<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><?= $role === 'manager' ? 'Manager' : 'Employee' ?></span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">Daily Report &amp; Attendance</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
      <span><?= h($username) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Daily Report &amp; Attendance</div>
        <div class="page-subtitle"><?= strtoupper($role) ?> · <?= date('l, d M Y') ?></div>
      </div>
      <a href="<?= $role === 'manager' ? 'dashboard_manager.php' : 'dashboard_employee.php' ?>" class="back-btn">
        <i class="fas fa-arrow-left" style="font-size:11px"></i> Back
      </a>
    </div>

    <?php if ($message): ?>
      <?php $ac = $message_type==='success'?'alert-success-custom':($message_type==='warning'?'alert-warning-custom':'alert-error-custom'); $ai = $message_type==='success'?'fa-check-circle':'fa-exclamation-circle'; ?>
      <div class="alert-custom <?= $ac ?>"><i class="fas <?= $ai ?>" style="margin-top:1px"></i><span><?= h($message) ?></span></div>
    <?php endif; ?>

    <?php if ($role === 'employee'): ?>
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-clock"></i> Today's Status</div>
        <?php if ($locked): ?>
          <span class="badge-custom badge-success"><i class="fas fa-lock"></i> Approved &amp; Locked</span>
        <?php elseif ($evening_submitted): ?>
          <span class="badge-custom badge-warning"><i class="fas fa-hourglass-half"></i> Pending Approval</span>
        <?php elseif ($morning_submitted): ?>
          <span class="badge-custom badge-blue"><i class="fas fa-sun"></i> Morning Submitted</span>
        <?php else: ?>
          <span class="badge-custom badge-purple"><i class="fas fa-circle-dot"></i> Not Started</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body">
        <div class="status-track">
          <div class="status-step">
            <div class="step-dot <?= $morning_submitted?($locked?'locked':'done'):'active' ?>">
              <i class="fas <?= $morning_submitted?'fa-check':'fa-sun' ?>"></i>
            </div>
            <div class="step-label">Morning</div>
            <?php if (!empty($today_report['login_time'])): ?>
              <div class="step-time"><?= date('h:i A', strtotime($today_report['login_time'])) ?></div>
            <?php endif; ?>
          </div>
          <div class="status-step">
            <div class="step-dot <?= $evening_submitted?($locked?'locked':'done'):($morning_submitted?'active':'') ?>">
              <i class="fas <?= $evening_submitted?'fa-check':'fa-moon' ?>"></i>
            </div>
            <div class="step-label">Evening</div>
            <?php if (!empty($today_report['logout_time'])): ?>
              <div class="step-time"><?= date('h:i A', strtotime($today_report['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 (!$morning_submitted && !$locked): ?>
        <!-- MORNING FORM -->
        <div id="cameraSection">
          <!-- Form validation errors only — no permission warnings -->
          <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>

          <!-- Camera error with retry (only shows if camera truly fails) -->
          <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 btn-warning" onclick="location.reload()">
              <i class="fas fa-redo"></i> Tap to Retry
            </button>
          </div>

          <div class="form-grid" style="margin-bottom:14px">
            <div class="form-group" style="margin-bottom:0">
              <label class="form-label">Location Type</label>
              <select id="location_type" class="form-control" required>
                <option value="">— Select —</option>
                <option>Office</option>
                <option>Client Visit</option>
                <option>Field Work</option>
                <option>Work From Home</option>
              </select>
            </div>
            <div class="form-group" style="margin-bottom:0;display:none" id="clientNameWrap">
              <label class="form-label">Client Name</label>
              <input type="text" id="client_name" class="form-control" placeholder="Enter client name">
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Morning Plan <span style="color:var(--red)">*</span></label>
            <textarea id="morning" class="form-control" placeholder="Describe your plan for today…" required></textarea>
          </div>

          <!-- Camera live view -->
          <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>
            <canvas id="canvas"></canvas>
            <div class="camera-overlay" id="cameraOverlay" style="display:none"><i class="fas fa-circle" style="color:#ef4444;font-size:8px"></i> Live</div>
          </div>
          <img id="photoPreview" alt="Selfie preview">

          <div style="display:flex;flex-direction:column;gap:10px;margin-top:14px">
            <button type="button" class="btn btn-primary btn-block btn-lg" id="captureBtn" onclick="capturePhoto()" disabled>
              <i class="fas fa-camera"></i> Capture Selfie
            </button>
            <div style="display:none;gap:10px" id="afterCaptureBtns">
              <button type="button" class="btn btn-success btn-block btn-lg" onclick="submitMorning()">
                <i class="fas fa-sign-in-alt"></i> Submit Morning Plan
              </button>
              <button type="button" class="btn btn-outline btn-lg" onclick="retakePhoto()" style="flex-shrink:0;padding:12px 18px">
                <i class="fas fa-redo"></i> Retake
              </button>
            </div>
          </div>
        </div>

        <?php elseif (!$evening_submitted && !$locked): ?>
        <!-- EVENING FORM -->
        <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="form-grid">
            <div class="form-group">
              <label class="form-label">Hits <span style="color:var(--red)">*</span></label>
              <textarea name="hits" class="form-control" placeholder="What did you achieve today?" required></textarea>
            </div>
            <div class="form-group">
              <label class="form-label">Missed</label>
              <textarea name="missed" class="form-control" placeholder="What was missed?"></textarea>
            </div>
          </div>
          <div class="form-grid">
            <div class="form-group">
              <label class="form-label">Carry Forward</label>
              <textarea name="carry_forward" class="form-control" placeholder="Tasks to carry forward…"></textarea>
            </div>
            <div class="form-group">
              <label class="form-label">Daily Summary</label>
              <textarea name="daily_summary" class="form-control" placeholder="Overall summary…"></textarea>
            </div>
          </div>
          <div style="display:flex;gap:10px;margin-top:4px">
            <button type="button" class="btn btn-outline btn-block" id="captureLocBtn" onclick="captureEveningLocation()">
              <i class="fas fa-map-marker-alt"></i> Capture Location
            </button>
            <button type="button" class="btn btn-primary btn-block" onclick="submitEvening()" id="submitEveningBtn" disabled>
              <i class="fas fa-moon"></i> Submit Evening Report
            </button>
          </div>
          <input type="hidden" name="action" value="evening">
          <input type="hidden" name="lat" id="evening_lat">
          <input type="hidden" name="lng" id="evening_lng">
        </form>

        <?php else: ?>
        <div style="text-align:center;padding:24px">
          <div style="width:56px;height:56px;border-radius:50%;background:<?= $locked?'#fef3c7':'#d1fae5' ?>;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;font-size:22px">
            <i class="fas <?= $locked?'fa-lock':'fa-check-circle' ?>" style="color:<?= $locked?'#d97706':'#059669' ?>"></i>
          </div>
          <div style="font-size:15px;font-weight:700;color:var(--ink);margin-bottom:4px"><?= $locked?'Report Approved & Locked':'Report Submitted — Pending Approval' ?></div>
          <div style="font-size:13px;color:var(--muted)">No further action needed for today.</div>
          <?php if (!empty($today_report['manager_remark'])): ?>
            <div style="margin-top:14px;background:#f1f5f9;border-radius:var(--radius-sm);padding:10px 14px;font-size:13px;color:var(--ink-2);text-align:left">
              <strong>Manager's Remark:</strong> <?= h($today_report['manager_remark']) ?>
            </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($role === 'manager'): ?>
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-clipboard-check"></i> Pending Approvals</div>
        <?php if (!empty($pending_reports)): ?>
          <span class="pending-badge"><i class="fas fa-hourglass-half"></i> <?= count($pending_reports) ?> pending</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($pending_reports)): ?>
          <div class="empty-state"><i class="fas fa-check-double"></i><p>All reports reviewed. Nothing pending.</p></div>
        <?php else: ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr>
              <th>Date</th><th>Employee</th><th>Morning Plan</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>Login Map</th><th>Logout Map</th><th>Action</th>
            </tr></thead>
            <tbody>
              <?php foreach ($pending_reports as $r): ?>
              <tr>
                <td style="white-space:nowrap;font-weight:600"><?= date('d M Y', strtotime($r['report_date'])) ?></td>
                <td style="white-space:nowrap"><?= h($r['employee_name']??'') ?></td>
                <td style="max-width:140px;font-size:12px"><?= nl2br(h($r['Morning']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['Hits']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['Missed']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['carry forward']??'')) ?></td>
                <td style="max-width:140px;font-size:12px"><?= nl2br(h($r['daily_summary']??'')) ?></td>
                <td><?= h($r['location_type']??'') ?></td>
                <td><?= h($r['client_name']??'') ?></td>
                <td style="white-space:nowrap;font-size:12px"><?= h($r['login_time']??'') ?></td>
                <td style="white-space:nowrap;font-size:12px"><?= h($r['logout_time']??'') ?></td>
                <td><?php if(!empty($r['photo_path'])): ?><a href="<?= h($r['photo_path']) ?>" target="_blank" class="photo-link"><i class="fas fa-image"></i> View</a><?php else: ?>—<?php endif; ?></td>
                <td><?php if(!empty($r['latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['latitude'] ?>,<?= $r['longitude']??'' ?>" target="_blank" class="map-link"><i class="fas fa-map-marker-alt"></i> Map</a><?php else: ?>—<?php endif; ?></td>
                <td><?php if(!empty($r['logout_latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['logout_latitude'] ?>,<?= $r['logout_longitude']??'' ?>" target="_blank" class="map-link"><i class="fas fa-map-marker-alt"></i> Map</a><?php else: ?>—<?php endif; ?></td>
                <td style="min-width:180px">
                  <form method="POST" class="approve-form">
                    <input type="hidden" name="action" value="approve_report">
                    <input type="hidden" name="report_user_id" value="<?= h($r['user_id']) ?>">
                    <input type="hidden" name="report_date" value="<?= h($r['report_date']) ?>">
                    <select name="new_status" class="form-control" required>
                      <option value="">— Select —</option>
                      <option value="Approved">✓ Approve</option>
                      <option value="Rejected">✗ Reject</option>
                    </select>
                    <textarea name="manager_remark" class="form-control" placeholder="Remark (optional)"></textarea>
                    <button type="submit" class="btn btn-primary" style="width:100%;padding:8px">Submit</button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <form method="GET" id="filterForm">
      <div class="filter-bar">
        <div class="filter-group">
          <label style="font-size:12px;font-weight:600;color:var(--muted)">View</label>
          <select name="view" class="filter-select" onchange="document.getElementById('filterForm').submit()">
            <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="filter-group">
          <label style="font-size:12px;font-weight:600;color:var(--muted)">From</label>
          <input type="date" name="from" class="filter-date" value="<?= h($from) ?>">
          <label style="font-size:12px;font-weight:600;color:var(--muted)">To</label>
          <input type="date" name="to" class="filter-date" value="<?= h($to) ?>">
          <button type="submit" class="btn btn-primary" style="padding:7px 16px;font-size:12px"><i class="fas fa-filter"></i> Filter</button>
        </div>
        <div class="filter-spacer"></div>
        <div class="export-btns">
          <a href="?export=excel&view=<?= h($view) ?>&from=<?= h($from) ?>&to=<?= h($to) ?>" class="btn btn-success" style="padding:7px 14px;font-size:12px"><i class="fas fa-file-excel"></i> Excel</a>
          <a href="?export=pdf&view=<?= h($view) ?>&from=<?= h($from) ?>&to=<?= h($to) ?>"   class="btn btn-danger"  style="padding:7px 14px;font-size:12px"><i class="fas fa-file-pdf"></i> PDF</a>
        </div>
      </div>
    </form>

    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-history"></i> Report History</div>
        <?php if (!empty($reports)): ?>
          <span style="font-size:11px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 10px;border-radius:20px"><?= count($reports) ?> records</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($reports)): ?>
          <div class="empty-state"><i class="fas fa-clipboard-list"></i><p>No reports found for this period.</p></div>
        <?php else: ?>
        <div class="tbl-wrap">
          <table class="dash-table">
            <thead><tr>
              <th>Date</th>
              <?php if ($role==='manager'): ?><th>Employee</th><?php endif; ?>
              <th>Morning Plan</th><th>Hits</th><th>Missed</th><th>Carry</th>
              <th>Summary</th><th>Status</th><th>Manager Comment</th>
              <th>Location</th><th>Client</th><th>Login</th><th>Logout</th>
              <th>Photo</th><th>Login Map</th><th>Logout Map</th>
            </tr></thead>
            <tbody>
              <?php foreach ($reports as $r):
                $st = $r['approval_status']??'Pending';
                $bc = $st==='Approved'?'badge-success':($st==='Rejected'?'badge-danger':'badge-warning');
              ?>
              <tr>
                <td style="white-space:nowrap;font-weight:600"><?= date('d M Y', strtotime($r['report_date'])) ?></td>
                <?php if ($role==='manager'): ?><td style="white-space:nowrap"><?= h($r['employee_name']??'') ?></td><?php endif; ?>
                <td style="max-width:140px;font-size:12px"><?= nl2br(h($r['Morning']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['Hits']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['Missed']??'')) ?></td>
                <td style="max-width:120px;font-size:12px"><?= nl2br(h($r['carry forward']??'')) ?></td>
                <td style="max-width:140px;font-size:12px"><?= nl2br(h($r['daily_summary']??'')) ?></td>
                <td><span class="badge-custom <?= $bc ?>"><?= h($st) ?></span></td>
                <td style="font-size:12px;max-width:140px"><?= !empty($r['manager_remark'])?h($r['manager_remark']):'<span style="color:var(--muted);font-style:italic">—</span>' ?></td>
                <td><?= h($r['location_type']??'') ?></td>
                <td><?= h($r['client_name']??'') ?></td>
                <td style="white-space:nowrap;font-size:12px"><?= h($r['login_time']??'') ?></td>
                <td style="white-space:nowrap;font-size:12px"><?= h($r['logout_time']??'') ?></td>
                <td><?php if(!empty($r['photo_path'])): ?><a href="<?= h($r['photo_path']) ?>" target="_blank" class="photo-link"><i class="fas fa-image"></i> View</a><?php else: ?>—<?php endif; ?></td>
                <td><?php if(!empty($r['latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['latitude'] ?>,<?= $r['longitude']??'' ?>" target="_blank" class="map-link"><i class="fas fa-map-marker-alt"></i> Map</a><?php else: ?>—<?php endif; ?></td>
                <td><?php if(!empty($r['logout_latitude'])): ?><a href="https://www.google.com/maps?q=<?= $r['logout_latitude'] ?>,<?= $r['logout_longitude']??'' ?>" target="_blank" class="map-link"><i class="fas fa-map-marker-alt"></i> Map</a><?php else: ?>—<?php endif; ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
</div>

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

<script>
/* ── BACK BUTTON ── */
history.replaceState({p:'r'},'',location.href);
history.pushState({p:'r'},'',location.href);
window.addEventListener('popstate',function(){history.pushState({p:'r'},'',location.href);});

/* ── SIDEBAR ── */
var sidebar=document.getElementById('sidebar');
var overlay=document.getElementById('sidebarOverlay');
function isMob(){return window.innerWidth<=768;}
function openSidebar(){sidebar.classList.remove('closed');if(isMob()){overlay.classList.add('show');document.body.style.overflow='hidden';}}
function closeSidebar(){sidebar.classList.add('closed');overlay.classList.remove('show');document.body.style.overflow='';}
function toggleSidebar(){sidebar.classList.contains('closed')?openSidebar():closeSidebar();}
window.addEventListener('resize',function(){if(!isMob()){sidebar.classList.remove('closed');overlay.classList.remove('show');document.body.style.overflow='';}});
if(!isMob())sidebar.classList.remove('closed');

/* ── FORM VALIDATION ERRORS ── */
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 — start immediately, no permission UI
   Flutter app already granted permission on launch.
   We just call getUserMedia and go.
══════════════════════════════════════════════ */
var video        = document.getElementById('video');
var canvas       = document.getElementById('canvas');
var photoPreview = document.getElementById('photoPreview');
var captureBtn   = document.getElementById('captureBtn');
var afterCapture = document.getElementById('afterCaptureBtns');
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 locType      = document.getElementById('location_type');
var clientWrap   = document.getElementById('clientNameWrap');
var cameraSection= document.getElementById('cameraSection');
var capturedPhoto= '';
var cameraReady  = false;

if(locType){
  locType.addEventListener('change',function(){
    if(clientWrap)clientWrap.style.display=this.value==='Client Visit'?'flex':'none';
  });
}

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(captureBtn){captureBtn.disabled=true;captureBtn.style.display='none';}
}

if(video){
  /* Polyfill mediaDevices for older Android WebView */
  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;
    }
    /* Try 3 constraint sets — bare {video:true} works on most Android WebViews */
    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){}
        /* Camera is live */
        cameraReady=true;
        if(cameraLoading)cameraLoading.style.display='none';
        video.style.display='block';
        if(cameraOverlay)cameraOverlay.style.display='block';
        if(captureBtn)captureBtn.disabled=false;
        lastErr=null;
        break;
      }catch(err){
        lastErr=err;
        /* NotAllowed = truly denied, stop trying */
        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 go to App Settings → Permissions → Camera and allow, then reopen the app.');
      }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 app is using HTTPS.');
      }else{
        showCameraError('Camera error: '+(lastErr.message||n)+'. Tap Retry.');
      }
    }
  })();
}

function capturePhoto(){
  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);
  capturedPhoto=canvas.toDataURL('image/jpeg',0.85);
  photoPreview.src=capturedPhoto;
  photoPreview.style.display='block';
  video.style.display='none';
  if(cameraOverlay)cameraOverlay.style.display='none';
  if(captureBtn)captureBtn.style.display='none';
  if(afterCapture)afterCapture.style.display='flex';
  hideErr('morningError');
}

function retakePhoto(){
  capturedPhoto='';
  photoPreview.style.display='none';
  video.style.display='block';
  if(cameraOverlay)cameraOverlay.style.display='block';
  if(captureBtn){captureBtn.style.display='flex';}
  if(afterCapture)afterCapture.style.display='none';
}

/* ══════════════════════════════════════════════
   LOCATION — get silently, no banners/prompts
   Flutter already granted permission.
══════════════════════════════════════════════ */
function getLocation(){
  return new Promise(function(resolve,reject){
    if(!navigator.geolocation){reject('no-geo');return;}
    navigator.geolocation.getCurrentPosition(
      function(pos){resolve({lat:pos.coords.latitude,lng:pos.coords.longitude});},
      function(err){reject(err);},
      {enableHighAccuracy:true,timeout:20000,maximumAge:0}
    );
  });
}

/* ── MORNING SUBMIT ── */
async function submitMorning(){
  if(!locType||!locType.value){showErr('morningError','morningErrorMsg','Please select a location type.','warning');return;}
  if(locType.value==='Client Visit'&&!document.getElementById('client_name').value.trim()){showErr('morningError','morningErrorMsg','Please enter the client name.','warning');return;}
  if(!document.getElementById('morning').value.trim()){showErr('morningError','morningErrorMsg','Please enter your morning plan.','warning');return;}
  if(!capturedPhoto){showErr('morningError','morningErrorMsg','Please capture your selfie first.','warning');return;}

  hideErr('morningError');
  document.getElementById('loadingText').textContent='Getting location…';
  document.getElementById('loadingOverlay').classList.add('show');
  if(cameraSection)cameraSection.style.display='none';

  var lat='',lng='';
  try{var loc=await getLocation();lat=loc.lat;lng=loc.lng;}catch(e){/* location failed silently — submit without coords */}

  document.getElementById('loadingText').textContent='Submitting…';
  var form=document.createElement('form');form.method='POST';form.style.display='none';
  function f(n,v){var i=document.createElement('input');i.type='hidden';i.name=n;i.value=v||'';form.appendChild(i);}
  f('action','morning');f('lat',lat);f('lng',lng);
  f('photo_data',capturedPhoto);
  f('location_type',locType.value);
  f('client_name',document.getElementById('client_name')?document.getElementById('client_name').value:'');
  f('morning',document.getElementById('morning').value);
  document.body.appendChild(form);form.submit();
}

/* ── EVENING LOCATION ── */
var eveningLocCaptured=false;

async function captureEveningLocation(){
  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{
    var loc=await getLocation();
    document.getElementById('evening_lat').value=loc.lat;
    document.getElementById('evening_lng').value=loc.lng;
    eveningLocCaptured=true;
    document.getElementById('submitEveningBtn').disabled=false;
    if(btn){btn.innerHTML='<i class="fas fa-check-circle"></i> Location Captured';btn.classList.remove('btn-outline');btn.classList.add('btn-success');btn.disabled=false;}
    if(locStatus){locStatus.className='loc-status got';locStatusMsg.textContent='Location captured successfully.';}
  }catch(err){
    if(btn){btn.disabled=false;btn.innerHTML='<i class="fas fa-map-marker-alt"></i> Retry Location';}
    if(locStatus){locStatus.className='loc-status failed';locStatusMsg.textContent='Could not get location. Tap Retry Location.';}
    /* Still allow submit without location if user taps retry and it fails again */
    eveningLocCaptured=false;
  }
}

function submitEvening(){
  var hits=document.querySelector('[name="hits"]');
  if(hits&&!hits.value.trim()){showErr('eveningError','eveningErrorMsg','Please fill in the Hits field.','warning');return;}
  if(!eveningLocCaptured){showErr('eveningError','eveningErrorMsg','Please capture your 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>