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

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

$manager_id = $_SESSION['user_id']; // users.id is VARCHAR(11) -> always treat as STRING, never bind as "i"
$manager_username = trim($_SESSION['username'] ?? '');

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

/* ================= MANAGER INFO (moved up: needed before any team query) ================= */
$mgr_stmt = $conn->prepare("SELECT first_name, last_name, photo FROM users WHERE id=?");
$mgr_stmt->bind_param("s", $manager_id);
$mgr_stmt->execute();
$manager_info = $mgr_stmt->get_result()->fetch_assoc();
$mgr_stmt->close();

$manager_full_name = trim(($manager_info['first_name'] ?? '') . ' ' . ($manager_info['last_name'] ?? ''));
$manager_name       = $manager_full_name !== '' ? $manager_full_name : $manager_username;

/*
 * FIX (matches the proven-correct pattern from myteam.php / dashboard_manager.php):
 *
 * This file previously filtered every query by
 *   LOWER(u.reporting_manager) = LOWER(?)   -- bound to the manager's USERNAME only
 *
 * `reporting_manager` is stored inconsistently in this database — sometimes
 * the manager's username, sometimes their full name. Matching against the
 * username alone silently dropped real team members whenever
 * reporting_manager held a full name instead, which is exactly the
 * "assigned employees not mapping correctly" symptom. We now match
 * against BOTH, everywhere below: the employee list, the Excel export,
 * the main report list, the monthly attendance rollup, and the approval
 * ownership check.
 */
function mgrMatchSQL($alias = '') {
    $col = $alias !== '' ? "{$alias}.reporting_manager" : "reporting_manager";
    return "(LOWER(TRIM({$col})) = LOWER(TRIM(?)) OR LOWER(TRIM({$col})) = LOWER(TRIM(?)))";
}
function safeMatchValue($val) {
    $val = trim((string)$val);
    // Never let a blank value match rows that also have a blank reporting_manager.
    return $val !== '' ? $val : "\0__no_match__\0";
}

$mgr_match_username = safeMatchValue($manager_username);
$mgr_match_fullname = safeMatchValue($manager_full_name);

$upload_path = "uploads/";
$message = "";
$message_type = "success";

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

function classifyAttendance($login_time, $logout_time, $office_start_time, $half_day_cutoff_time) {
    $is_late = false; $is_half_day = false;
    if (!empty($login_time)) {
        $is_late = date('H:i:s', strtotime($login_time)) > $office_start_time;
    }
    if (!empty($logout_time)) {
        $is_half_day = date('H:i:s', strtotime($logout_time)) <= $half_day_cutoff_time;
    }
    return ['late' => $is_late, 'half_day' => $is_half_day];
}

/* ================= FILTERS (daily report review) ================= */
$selected_date = $_GET['report_date'] ?? date('Y-m-d');
$selected_emp  = $_GET['emp_id'] ?? 'all';
$search        = $_GET['search'] ?? '';

/* ================= EMPLOYEE LIST / TEAM DETAILS (needed early for emp_id validation) =================
 * Uses the fixed mgrMatchSQL() matching (username OR full name) and pulls
 * the fields needed for the "Team Details" card: designation, division,
 * level, location, mobile, email, photo, status. */
$emp_stmt = $conn->prepare(
    "SELECT id, CONCAT(first_name,' ',last_name) AS name, designation, division, level,
            location, mobileno, email, photo, status
     FROM users
     WHERE " . mgrMatchSQL() . " AND status='active'
     ORDER BY name"
);
$emp_stmt->bind_param("ss", $mgr_match_username, $mgr_match_fullname);
$emp_stmt->execute();
$employees = $emp_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$emp_stmt->close();

// SECURITY/CORRECTNESS: if emp_id filter is set, make sure it actually belongs
// to this manager's own team before using it in any query. Prevents
// URL-tampering (?emp_id=someone_elses_id) from leaking other teams' reports.
if ($selected_emp !== 'all') {
    $valid_emp_ids = array_column($employees, 'id');
    if (!in_array($selected_emp, $valid_emp_ids, true)) {
        $selected_emp = 'all'; // not one of this manager's employees -> ignore the filter
    }
}

/* ================= MONTHLY ATTENDANCE =================
 * Separate filter set (att_month / att_emp) so it doesn't collide with
 * the daily report review filters (report_date / emp_id) above.
 * - att_emp = 'all'  -> team-wide monthly roll-up (check-ins, check-outs,
 *   late days, half-days per employee)
 * - att_emp = <id>   -> that employee's full day-by-day breakdown for
 *   the month, with the same office-timing Late/Half-Day rules used
 *   elsewhere in the system.
 */
$att_month      = $_GET['att_month'] ?? date('Y-m');
$att_monthStart = $att_month . '-01';
$att_monthEnd   = date('Y-m-t', strtotime($att_monthStart));
$att_emp        = $_GET['att_emp'] ?? 'all';

if ($att_emp !== 'all') {
    $valid_emp_ids_att = array_column($employees, 'id');
    if (!in_array($att_emp, $valid_emp_ids_att, true)) {
        $att_emp = 'all';
    }
}

$team_monthly_attendance = [];
$att_emp_daily = [];
$att_emp_name  = '';

if (!empty($employees)) {
    $emp_ids = array_column($employees, 'id');

    // Initialise every team member at zero so employees with no records
    // this month still show up in the summary table.
    foreach ($employees as $e) {
        $team_monthly_attendance[$e['id']] = [
            'name' => $e['name'], 'checkins' => 0, 'checkouts' => 0, 'late' => 0, 'half_day' => 0,
        ];
    }

    $placeholders = implode(',', array_fill(0, count($emp_ids), '?'));
    $types_att    = str_repeat('s', count($emp_ids)) . 'ss';
    $sql_att      = "SELECT user_id, report_date, login_time, logout_time
                      FROM daily_reports
                      WHERE user_id IN ($placeholders) AND report_date BETWEEN ? AND ?";
    $stmt_att = $conn->prepare($sql_att);
    $params_att = array_merge($emp_ids, [$att_monthStart, $att_monthEnd]);
    $stmt_att->bind_param($types_att, ...$params_att);
    $stmt_att->execute();
    $res_att = $stmt_att->get_result();
    while ($row = $res_att->fetch_assoc()) {
        $uid = $row['user_id'];
        if (!isset($team_monthly_attendance[$uid])) continue;
        $flags = classifyAttendance($row['login_time'], $row['logout_time'], $office_start_time, $half_day_cutoff_time);
        if (!empty($row['login_time']))  { $team_monthly_attendance[$uid]['checkins']++;  if ($flags['late'])     $team_monthly_attendance[$uid]['late']++; }
        if (!empty($row['logout_time'])) { $team_monthly_attendance[$uid]['checkouts']++; if ($flags['half_day']) $team_monthly_attendance[$uid]['half_day']++; }
    }
    $stmt_att->close();

    if ($att_emp !== 'all') {
        $stmt = $conn->prepare(
            "SELECT report_date, login_time, logout_time, latitude, longitude,
                    logout_latitude, logout_longitude, photo_path, logout_photo_path
             FROM daily_reports WHERE user_id=? AND report_date BETWEEN ? AND ?
             ORDER BY report_date DESC"
        );
        $stmt->bind_param("sss", $att_emp, $att_monthStart, $att_monthEnd);
        $stmt->execute();
        $att_emp_daily = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        foreach ($att_emp_daily as &$d) {
            $flags = classifyAttendance($d['login_time'], $d['logout_time'], $office_start_time, $half_day_cutoff_time);
            $d['is_late'] = $flags['late']; $d['is_half_day'] = $flags['half_day'];
        }
        unset($d);
        foreach ($employees as $e) { if ($e['id'] == $att_emp) { $att_emp_name = $e['name']; break; } }
    }
}

/* ================= EXPORT ================= */
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=manager_daily_reports_$selected_date.xls");

    $sql_export = "
    SELECT 
        CONCAT(u.first_name,' ',u.last_name) AS emp_name,
        dr.location_type AS Location,
        dr.client_name,
        dr.Morning, dr.Hits, dr.Missed, dr.`carry forward`,
        dr.daily_summary, dr.login_time, dr.logout_time,
        dr.photo_path, dr.latitude, dr.longitude,
        dr.logout_latitude, dr.logout_longitude, dr.approval_status
    FROM daily_reports dr
    JOIN users u ON dr.user_id = u.id
    WHERE " . mgrMatchSQL('u') . " AND dr.report_date = ?";

    $params = [$mgr_match_username, $mgr_match_fullname, $selected_date];
    $types  = "sss";

    if ($selected_emp !== 'all') { $sql_export .= " AND dr.user_id = ?"; $params[] = $selected_emp; $types .= "s"; }
    if (!empty($search)) {
        $sql_export .= " AND (dr.Morning LIKE ? OR dr.Hits LIKE ? OR dr.Missed LIKE ? OR dr.`carry forward` LIKE ? OR dr.daily_summary LIKE ?)";
        $like = "%$search%";
        $params = array_merge($params, [$like,$like,$like,$like,$like]);
        $types .= "sssss";
    }

    $stmt = $conn->prepare($sql_export);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    echo "Employee\tLocation\tClient Name\tMorning\tHits\tMissed\tCarry Forward\tSummary\tLogin Time\tLogout Time\tPhoto Path\tLatitude\tLongitude\tLogout Latitude\tLogout Longitude\tStatus\n";
    while ($row = $result->fetch_assoc()) {
        echo $row['emp_name']."\t".$row['Location']."\t".$row['client_name']."\t".$row['Morning']."\t".$row['Hits']."\t".$row['Missed']."\t".$row['carry forward']."\t".$row['daily_summary']."\t".$row['login_time']."\t".$row['logout_time']."\t".$row['photo_path']."\t".$row['latitude']."\t".$row['longitude']."\t".$row['logout_latitude']."\t".$row['logout_longitude']."\t".$row['approval_status']."\n";
    }
    exit;
}

/* ================= APPROVAL ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_id'])) {
    $report_id = (int)$_POST['report_id'];
    $action    = $_POST['action'];
    $remark    = $_POST['manager_remark'];
    $status    = ($action === 'approve') ? 'Approved' : 'Rejected';

    /*
     * AUTHORIZATION CHECK: verify the report actually belongs to one of
     * this manager's own team members (matched on username OR full name)
     * before allowing the update. Without this, a POSTed report_id
     * belonging to any employee, in any team, could be approved/rejected
     * by anyone.
     */
    $chk = $conn->prepare("SELECT dr.id FROM daily_reports dr JOIN users u ON dr.user_id = u.id WHERE dr.id = ? AND " . mgrMatchSQL('u'));
    $chk->bind_param("iss", $report_id, $mgr_match_username, $mgr_match_fullname);
    $chk->execute();
    $is_team_report = $chk->get_result()->fetch_assoc();
    $chk->close();

    if (!$is_team_report) {
        $message = "You are not authorized to update this report.";
        $message_type = "danger";
    } else {
        $stmt = $conn->prepare("UPDATE daily_reports SET approval_status=?, manager_remark=?, approved_at=NOW() WHERE id=?");
        $stmt->bind_param("ssi", $status, $remark, $report_id);
        if ($stmt->execute()) {
            $message = "Report <strong>$status</strong> successfully!";
            $message_type = ($status === 'Approved') ? 'success' : 'danger';
        }
    }
}

/* ================= REPORT QUERY (team reports for the selected date) ================= */
$sql = "SELECT dr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name, u.photo
        FROM daily_reports dr JOIN users u ON dr.user_id = u.id
        WHERE " . mgrMatchSQL('u') . " AND dr.report_date=?";
$params = [$mgr_match_username, $mgr_match_fullname, $selected_date];
$types  = "sss";

if ($selected_emp !== 'all') { $sql .= " AND dr.user_id=?"; $params[] = $selected_emp; $types .= "s"; }
if (!empty($search)) {
    $sql .= " AND (dr.Morning LIKE ? OR dr.Hits LIKE ? OR dr.Missed LIKE ? OR dr.`carry forward` LIKE ? OR dr.daily_summary LIKE ?)";
    $like = "%$search%";
    $params = array_merge($params, [$like,$like,$like,$like,$like]);
    $types .= "sssss";
}
$sql .= " ORDER BY dr.created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$reports = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

/* ================= SUMMARY ================= */
$total    = count($reports);
$approved = count(array_filter($reports, fn($r) => $r['approval_status'] === 'Approved'));
$rejected = count(array_filter($reports, fn($r) => $r['approval_status'] === 'Rejected'));
$pending  = count(array_filter($reports, fn($r) => $r['approval_status'] === 'Pending'));

/* ================= MY DAILY REPORT HISTORY (manager's own submitted reports) ================= */
$myh_stmt = $conn->prepare("SELECT id, report_date, location_type, client_name, daily_summary, approval_status, manager_remark
    FROM daily_reports WHERE user_id = ? ORDER BY report_date DESC LIMIT 15");
$myh_stmt->bind_param("s", $manager_id);
$myh_stmt->execute();
$my_history = $myh_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$myh_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 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{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}

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

/* ─── STAT CARDS ─── */
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;box-shadow:var(--shadow);display:flex;align-items:center;gap:13px;border-left:4px solid transparent;transition:transform .15s,box-shadow .15s}
.stat-card:hover{transform:translateY(-2px);box-shadow:var(--shadow-md)}
.stat-card.c-blue{border-color:#4f46e5}
.stat-card.c-green{border-color:var(--green)}
.stat-card.c-red{border-color:var(--red)}
.stat-card.c-amber{border-color:var(--amber)}
.stat-icon{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.c-blue .stat-icon{background:#eff6ff;color:#4f46e5}
.c-green .stat-icon{background:#d1fae5;color:var(--green)}
.c-red .stat-icon{background:#fee2e2;color:var(--red)}
.c-amber .stat-icon{background:#fef3c7;color:var(--amber)}
.stat-num{font-size:24px;font-weight:800;color:var(--ink);line-height:1;font-family:'DM Mono',monospace}
.stat-lbl{font-size:11px;color:var(--muted);margin-top:3px;font-weight:500}

/* ─── DASH CARD ─── */
.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:16px 18px}

/* ─── FILTER CARD ─── */
.filter-label{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;color:var(--muted);margin-bottom:10px;display:flex;align-items:center;gap:6px}
.filter-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end}
.fg{display:flex;flex-direction:column;gap:4px;flex:1;min-width:140px}
.fg label{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px}
.form-control,.form-select{border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;color:var(--ink);padding:8px 12px;font-family:'DM Sans',sans-serif;transition:border-color .15s;background:var(--bg);outline:none}
.form-control:focus,.form-select:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}

/* ─── REPORT GRID ─── */
.reports-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:18px}
.rcard{background:var(--surface);border:1.5px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;transition:transform .15s,box-shadow .15s}
.rcard:hover{transform:translateY(-3px);box-shadow:var(--shadow-md)}
.rcard.s-approved{border-color:rgba(5,150,105,.2)}
.rcard.s-rejected{border-color:rgba(220,38,38,.2)}
.rcard.s-pending{border-color:rgba(217,119,6,.2)}

.rcard-head{background:linear-gradient(135deg,#0f172a,#1e293b);padding:15px 16px;display:flex;align-items:center;gap:11px;position:relative;overflow:hidden}
.rcard-head::after{content:'';position:absolute;right:-20px;top:-20px;width:80px;height:80px;background:rgba(79,70,229,.14);border-radius:50%}
.rcard-avatar{width:46px;height:46px;flex-shrink:0;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,.14);position:relative;z-index:1}
.rcard-emp{flex:1;position:relative;z-index:1;min-width:0}
.rcard-name{font-size:.88rem;font-weight:700;color:#f1f5f9;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.rcard-meta{font-size:.7rem;color:#64748b;display:flex;gap:8px;flex-wrap:wrap;margin-top:3px}
.status-pill{padding:3px 10px;border-radius:20px;font-size:.66rem;font-weight:700;text-transform:uppercase;letter-spacing:.3px;flex-shrink:0;position:relative;z-index:1}
.sp-Approved{background:rgba(5,150,105,.2);color:#34d399;border:1px solid rgba(5,150,105,.3)}
.sp-Rejected{background:rgba(220,38,38,.2);color:#f87171;border:1px solid rgba(220,38,38,.3)}
.sp-Pending{background:rgba(217,119,6,.2);color:#fbbf24;border:1px solid rgba(217,119,6,.3)}

.sec{padding:10px 15px;border-bottom:1px solid var(--border)}
.sec-lbl{font-size:.63rem;font-weight:700;text-transform:uppercase;letter-spacing:.8px;display:flex;align-items:center;gap:5px;margin-bottom:5px}
.dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.sec-txt{font-size:.82rem;color:var(--ink-2);line-height:1.55;white-space:pre-wrap}
.sec-morning{background:#eff6ff}.sec-morning .sec-lbl{color:#1d4ed8}.sec-morning .dot{background:#3b82f6}
.sec-hits{background:#f0fdf4}.sec-hits .sec-lbl{color:#15803d}.sec-hits .dot{background:#22c55e}
.sec-missed{background:#fff1f2}.sec-missed .sec-lbl{color:#b91c1c}.sec-missed .dot{background:#f87171}
.sec-carry{background:#fffbeb}.sec-carry .sec-lbl{color:#b45309}.sec-carry .dot{background:#fbbf24}
.sec-summary{background:#f5f3ff}.sec-summary .sec-lbl{color:#5b21b6}.sec-summary .dot{background:#8b5cf6}

.time-strip{display:flex;background:#f8fafc;border-bottom:1px solid var(--border)}
.time-box{flex:1;padding:10px 8px;text-align:center;border-right:1px solid var(--border)}
.time-box:last-child{border-right:none}
.time-box-lbl{font-size:.6rem;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);margin-bottom:3px}
.time-box-val{font-size:.86rem;font-weight:700;color:var(--ink);font-family:'DM Mono',monospace}

.media-strip{display:flex;border-bottom:1px solid var(--border);background:#f8fafc}
.media-btn{flex:1;padding:10px 6px;display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;font-size:.67rem;font-weight:600;color:var(--muted);border-right:1px solid var(--border);transition:background .14s,color .14s;text-align:center}
.media-btn:last-child{border-right:none}
.media-btn i{font-size:.95rem}
.media-btn:hover{background:#eff6ff;color:var(--accent);text-decoration:none}
.media-btn.no-data{color:#cbd5e1;pointer-events:none}

.approval-area{padding:13px 15px;background:#fafafa}
.remark-box{width:100%;border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:8px 12px;font-size:.84rem;font-family:'DM Sans',sans-serif;resize:vertical;min-height:62px;margin-bottom:9px;background:#fff;transition:border-color .15s}
.remark-box:focus{border-color:var(--accent);outline:none}
.action-row{display:flex;gap:8px}
.btn-approve,.btn-reject{flex:1;padding:8px 10px;border:none;border-radius:var(--radius-sm);font-family:'DM Sans',sans-serif;font-weight:700;font-size:.8rem;cursor:pointer;transition:all .15s;display:inline-flex;align-items:center;justify-content:center;gap:5px}
.btn-approve{background:#d1fae5;color:#065f46}.btn-approve:hover{background:#059669;color:#fff}
.btn-reject{background:#fee2e2;color:#991b1b}.btn-reject:hover{background:#dc2626;color:#fff}

.remark-display{padding:12px 15px;background:#f8fafc}
.remark-display-lbl{font-size:.63rem;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin-bottom:4px}
.remark-display-txt{font-size:.82rem;color:var(--ink-2);line-height:1.5}

/* ─── 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-info-custom{background:#dbeafe;border-left:3px solid #1e40af;color:#1e40af}

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

.btn-filter{display:inline-flex;align-items:center;gap:7px;border:none;border-radius:var(--radius-sm);padding:8px 18px;font-size:13px;font-weight:600;cursor:pointer;transition:all .15s;background:var(--accent);color:#fff;font-family:'DM Sans',sans-serif}
.btn-filter:hover{background:#4338ca;transform:translateY(-1px)}
.btn-export{display:inline-flex;align-items:center;gap:7px;border:none;border-radius:var(--radius-sm);padding:8px 18px;font-size:13px;font-weight:600;cursor:pointer;transition:all .15s;background:var(--green);color:#fff;text-decoration:none;font-family:'DM Sans',sans-serif}
.btn-export:hover{background:#047857;color:#fff;transform:translateY(-1px)}

.empty-state{text-align:center;padding:56px 24px;color:var(--muted)}
.empty-state i{font-size:40px;display:block;margin-bottom:12px;opacity:.3}
.empty-state h5{font-size:15px;font-weight:700;color:var(--muted)}
.empty-state p{font-size:13px;margin-top:4px}

/* ─── TOAST ─── */
.toast-msg{position:fixed;top:16px;right:18px;z-index:9999;padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:0 6px 24px rgba(0,0,0,.13);animation:toastIn .28s ease;max-width:300px}
.toast-msg.success{background:#d1fae5;color:#166534;border:1px solid #bbf7d0}
.toast-msg.danger{background:#fee2e2;color:#991b1b;border:1px solid #fecaca}
@keyframes toastIn{from{opacity:0;transform:translateX(70px)}to{opacity:1;transform:translateX(0)}}

/* ─── TEAM DETAILS ─── */
.team-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px}
.team-card{background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:13px;display:flex;gap:10px;align-items:flex-start}
.team-avatar{width:44px;height:44px;border-radius:50%;object-fit:cover;border:2px solid var(--surface);box-shadow:var(--shadow);flex-shrink:0}
.team-info{min-width:0;flex:1}
.team-name{font-size:12.5px;font-weight:700;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.team-meta{font-size:10.5px;color:var(--muted);margin-top:2px;line-height:1.6}
.team-meta i{width:12px;color:var(--accent);margin-right:2px}
.team-view-btn{display:inline-flex;align-items:center;gap:4px;margin-top:7px;padding:4px 10px;border-radius:20px;font-size:10.5px;font-weight:700;background:#ede9fe;color:#5b21b6;text-decoration:none}
.team-view-btn:hover{background:#5b21b6;color:#fff;text-decoration:none}

/* ─── MONTHLY ATTENDANCE ─── */
.att-stats-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:10px;margin-bottom:16px}
.att-stat-mini{background:var(--bg);border:1px solid var(--border);border-radius:var(--radius-sm);padding:10px;text-align:center}
.att-stat-mini .num{font-size:19px;font-weight:800;font-family:'DM Mono',monospace}
.att-stat-mini .lbl{font-size:9.5px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-top:2px}
.pill{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:50px;font-size:10.5px;font-weight:700}
.pill-late{background:#fef3c7;color:#78350f}
.pill-half{background:#dbeafe;color:#1e3a8a}
.pill-ontime{background:#d1fae5;color:#065f46}
.pill-absent{background:#fee2e2;color:#991b1b}
.dash-table{width:100%;border-collapse:collapse;font-size:12.5px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.6px;padding:9px 12px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:9px 12px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}
.tbl-wrap{overflow-x:auto}
.emp-av-sm{width:24px;height:24px;border-radius:7px;background:#ede9fe;color:var(--accent);display:inline-flex;align-items:center;justify-content:center;font-weight:700;font-size:10px;flex-shrink:0}

/* ─── MY HISTORY TABLE ─── */
.hist-remark{font-size:11px;color:var(--muted);max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

@media(max-width:1060px){.stats-row{grid-template-columns:repeat(2,1fr)}.reports-grid{grid-template-columns:1fr}}
@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{padding:14px}.stats-row{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"><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>

  <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>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($manager_name, 0, 1)) ?></div>
      <span><?= h($manager_name) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title"><i class="fas fa-file-alt" style="color:var(--accent);margin-right:8px;font-size:18px"></i>Daily Reports</div>
      <div class="page-subtitle"><?= date('l, F j, Y', strtotime($selected_date)) ?> · Team Report Review</div>
    </div>

    <?php if ($message): ?>
      <div class="toast-msg <?= $message_type ?>" id="toastEl">
        <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : 'times-circle' ?>"></i>
        <?= $message ?>
      </div>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-row">
      <div class="stat-card c-blue">
        <div class="stat-icon"><i class="fas fa-file-alt"></i></div>
        <div><div class="stat-num"><?= $total ?></div><div class="stat-lbl">Total Reports</div></div>
      </div>
      <div class="stat-card c-green">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div><div class="stat-num"><?= $approved ?></div><div class="stat-lbl">Approved</div></div>
      </div>
      <div class="stat-card c-red">
        <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
        <div><div class="stat-num"><?= $rejected ?></div><div class="stat-lbl">Rejected</div></div>
      </div>
      <div class="stat-card c-amber">
        <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
        <div><div class="stat-num"><?= $pending ?></div><div class="stat-lbl">Pending</div></div>
      </div>
    </div>

    <!-- ═══ TEAM DETAILS ═══ -->
    <div class="dash-card" id="team-details">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-users"></i> Team Details</div>
        <span class="badge-custom badge-purple"><?= count($employees) ?> member<?= count($employees) !== 1 ? 's' : '' ?></span>
      </div>
      <div class="dash-card-body">
        <?php if (empty($employees)): ?>
          <div class="alert-custom alert-error-custom" style="margin:0"><i class="fas fa-info-circle me-2"></i>No team members found under your reporting line.</div>
        <?php else: ?>
          <div class="team-grid">
            <?php foreach ($employees as $e):
              $photo_ok = !empty($e['photo']) && file_exists($upload_path.$e['photo']);
              $photo_src = $photo_ok ? $upload_path.$e['photo'] : $upload_path.'default.png';
            ?>
              <div class="team-card">
                <img src="<?= h($photo_src) ?>" class="team-avatar" alt="">
                <div class="team-info">
                  <div class="team-name"><?= h($e['name']) ?></div>
                  <div class="team-meta">
                    <?php if (!empty($e['designation'])): ?><div><i class="fas fa-id-badge"></i><?= h($e['designation']) ?></div><?php endif; ?>
                    <?php if (!empty($e['division'])): ?><div><i class="fas fa-building"></i><?= h($e['division']) ?></div><?php endif; ?>
                    <?php if (!empty($e['level'])): ?><div><i class="fas fa-layer-group"></i>Level <?= h($e['level']) ?></div><?php endif; ?>
                    <?php if (!empty($e['location'])): ?><div><i class="fas fa-map-marker-alt"></i><?= h(ucfirst($e['location'])) ?></div><?php endif; ?>
                    <?php if (!empty($e['mobileno'])): ?><div><i class="fas fa-phone"></i><?= h($e['mobileno']) ?></div><?php endif; ?>
                  </div>
                  <a href="?att_emp=<?= urlencode($e['id']) ?>&att_month=<?= h($att_month) ?>#monthly-attendance" class="team-view-btn"><i class="fas fa-calendar-check"></i> View Attendance</a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- ═══ MONTHLY ATTENDANCE ═══ -->
    <div class="dash-card" id="monthly-attendance">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-calendar-days"></i> Monthly Attendance <span style="color:var(--muted);font-weight:500">· Check-in / Check-out</span></div>
        <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
          <!-- Preserve the daily-report filters so switching tabs doesn't reset them -->
          <input type="hidden" name="report_date" value="<?= h($selected_date) ?>">
          <input type="hidden" name="emp_id" value="<?= h($selected_emp) ?>">
          <input type="hidden" name="search" value="<?= h($search) ?>">
          <select name="att_emp" class="form-select" style="font-size:12.5px;padding:6px 10px">
            <option value="all" <?= $att_emp==='all'?'selected':'' ?>>All Employees (Summary)</option>
            <?php foreach ($employees as $e): ?>
              <option value="<?= h($e['id']) ?>" <?= $att_emp==$e['id']?'selected':'' ?>><?= h($e['name']) ?></option>
            <?php endforeach; ?>
          </select>
          <input type="month" name="att_month" value="<?= h($att_month) ?>" class="form-control" style="width:150px;font-size:12.5px;padding:6px 10px">
          <button type="submit" class="btn-filter" style="padding:6px 14px"><i class="fas fa-check"></i> Go</button>
        </form>
      </div>
      <div class="dash-card-body">
        <p style="font-size:11.5px;color:var(--muted);margin-bottom:14px">Office hours 9:30 AM – 6:30 PM · Check-in after 9:30 AM = <strong>Late</strong> · Check-out at/before 1:00 PM = <strong>Half Day</strong></p>

        <?php if ($att_emp === 'all'): ?>
          <!-- TEAM-WIDE MONTHLY SUMMARY -->
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead><tr><th>Employee</th><th>Check-ins</th><th>Check-outs</th><th>Late Days</th><th>Half Days</th><th>Detail</th></tr></thead>
              <tbody>
                <?php if (empty($team_monthly_attendance)): ?>
                  <tr><td colspan="6" style="text-align:center;padding:20px;color:var(--muted)">No team members found</td></tr>
                <?php else: foreach ($team_monthly_attendance as $uid => $row): ?>
                  <tr>
                    <td><div style="display:flex;align-items:center;gap:8px"><div class="emp-av-sm"><?= strtoupper(substr($row['name'],0,1)) ?></div><strong style="font-size:12px"><?= h($row['name']) ?></strong></div></td>
                    <td class="mono"><?= $row['checkins'] ?></td>
                    <td class="mono"><?= $row['checkouts'] ?></td>
                    <td><?= $row['late']>0 ? '<span class="pill pill-late">'.$row['late'].'</span>' : '<span style="color:var(--muted)">0</span>' ?></td>
                    <td><?= $row['half_day']>0 ? '<span class="pill pill-half">'.$row['half_day'].'</span>' : '<span style="color:var(--muted)">0</span>' ?></td>
                    <td><a href="?att_emp=<?= urlencode($uid) ?>&att_month=<?= h($att_month) ?>&report_date=<?= h($selected_date) ?>&emp_id=<?= h($selected_emp) ?>&search=<?= urlencode($search) ?>#monthly-attendance" class="btn btn-sm btn-outline-primary" style="font-size:11px">Day-by-day</a></td>
                  </tr>
                <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>

        <?php else: ?>
          <!-- SINGLE EMPLOYEE DAY-BY-DAY -->
          <?php
            $emp_checkins = 0; $emp_checkouts = 0; $emp_late = 0; $emp_half = 0;
            foreach ($att_emp_daily as $d) {
                if (!empty($d['login_time']))  { $emp_checkins++;  if ($d['is_late'])     $emp_late++; }
                if (!empty($d['logout_time'])) { $emp_checkouts++; if ($d['is_half_day']) $emp_half++; }
            }
          ?>
          <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:12px">
            <div style="font-size:13px;font-weight:700"><i class="fas fa-user" style="color:var(--accent);margin-right:6px"></i><?= h($att_emp_name) ?> · <?= date('F Y', strtotime($att_monthStart)) ?></div>
            <a href="?att_emp=all&att_month=<?= h($att_month) ?>&report_date=<?= h($selected_date) ?>&emp_id=<?= h($selected_emp) ?>&search=<?= urlencode($search) ?>#monthly-attendance" class="btn btn-sm btn-outline-secondary" style="font-size:11px"><i class="fas fa-arrow-left"></i> Back to Team Summary</a>
          </div>

          <div class="att-stats-row">
            <div class="att-stat-mini"><div class="num" style="color:var(--accent)"><?= $emp_checkins ?></div><div class="lbl">Check-ins</div></div>
            <div class="att-stat-mini"><div class="num" style="color:var(--green)"><?= $emp_checkouts ?></div><div class="lbl">Check-outs</div></div>
            <div class="att-stat-mini"><div class="num" style="color:var(--amber)"><?= $emp_late ?></div><div class="lbl">Late</div></div>
            <div class="att-stat-mini"><div class="num" style="color:#1e3a8a"><?= $emp_half ?></div><div class="lbl">Half Days</div></div>
          </div>

          <div class="tbl-wrap">
            <table class="dash-table">
              <thead><tr><th>Date</th><th>Check-in</th><th>Check-out</th><th>Status</th><th>Photo</th><th>Map In</th><th>Map Out</th></tr></thead>
              <tbody>
                <?php if (empty($att_emp_daily)): ?>
                  <tr><td colspan="7" style="text-align:center;padding:20px;color:var(--muted)">No attendance records for this month</td></tr>
                <?php else: foreach ($att_emp_daily as $d): ?>
                  <tr>
                    <td class="mono"><?= date('d M Y', strtotime($d['report_date'])) ?></td>
                    <td class="mono"><?= !empty($d['login_time']) ? date('h:i A', strtotime($d['login_time'])) : '—' ?></td>
                    <td class="mono"><?= !empty($d['logout_time']) ? date('h:i A', strtotime($d['logout_time'])) : '—' ?></td>
                    <td>
                      <?php if (empty($d['login_time'])): ?>
                        <span class="pill pill-absent">Absent</span>
                      <?php else: ?>
                        <?= $d['is_late'] ? '<span class="pill pill-late"><i class="fas fa-clock"></i> Late</span>' : '<span class="pill pill-ontime"><i class="fas fa-check"></i> On Time</span>' ?>
                        <?php if ($d['is_half_day']): ?><span class="pill pill-half"><i class="fas fa-hourglass-half"></i> Half Day</span><?php endif; ?>
                      <?php endif; ?>
                    </td>
                    <td>
                      <?php if (!empty($d['photo_path'])): ?><a href="<?= h($d['photo_path']) ?>" target="_blank" title="Check-in photo"><i class="fas fa-image text-primary"></i></a><?php endif; ?>
                      <?php if (!empty($d['logout_photo_path'])): ?> <a href="<?= h($d['logout_photo_path']) ?>" target="_blank" title="Check-out photo"><i class="fas fa-image text-success"></i></a><?php endif; ?>
                      <?php if (empty($d['photo_path']) && empty($d['logout_photo_path'])): ?>—<?php endif; ?>
                    </td>
                    <td><?php if (!empty($d['latitude']) && !empty($d['longitude'])): ?><a href="https://www.google.com/maps?q=<?= $d['latitude'] ?>,<?= $d['longitude'] ?>" target="_blank"><i class="fas fa-map-marker-alt text-danger"></i></a><?php else: ?>—<?php endif; ?></td>
                    <td><?php if (!empty($d['logout_latitude']) && !empty($d['logout_longitude'])): ?><a href="https://www.google.com/maps?q=<?= $d['logout_latitude'] ?>,<?= $d['logout_longitude'] ?>" target="_blank"><i class="fas fa-map-marker-alt text-danger"></i></a><?php else: ?>—<?php endif; ?></td>
                  </tr>
                <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- ═══ MY DAILY REPORT HISTORY (manager's own submissions) ═══ -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-user-clock"></i> My Daily Report History</div>
        <span class="badge-custom badge-info"><?= count($my_history) ?> recent</span>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($my_history)): ?>
          <div style="padding:16px 18px">
            <div class="alert-custom alert-info-custom" style="margin:0"><i class="fas fa-info-circle me-2"></i>No daily reports submitted by you yet.</div>
          </div>
        <?php else: ?>
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead>
                <tr><th>Date</th><th>Location</th><th>Client</th><th>Summary</th><th>Status</th><th>Remark</th></tr>
              </thead>
              <tbody>
                <?php foreach ($my_history as $mh):
                  $mh_status = $mh['approval_status'] ?? 'Pending';
                  $mh_badge = $mh_status === 'Approved' ? 'badge-success' : ($mh_status === 'Rejected' ? 'badge-danger' : 'badge-warning');
                ?>
                  <tr>
                    <td style="font-size:12px;white-space:nowrap"><?= h(date('d M Y', strtotime($mh['report_date']))) ?></td>
                    <td style="font-size:12px"><?= h($mh['location_type'] ?? '—') ?></td>
                    <td style="font-size:12px"><?= h($mh['client_name'] ?? '—') ?></td>
                    <td style="max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px"><?= h(substr($mh['daily_summary'] ?? '—', 0, 60)) ?></td>
                    <td><span class="badge-custom <?= $mh_badge ?>"><?= h($mh_status) ?></span></td>
                    <td class="hist-remark"><?= !empty($mh['manager_remark']) ? h($mh['manager_remark']) : '—' ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- FILTER -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-filter"></i> Filters & Export</div>
      </div>
      <div class="dash-card-body">
        <form method="GET">
          <!-- Preserve the monthly-attendance filters too -->
          <input type="hidden" name="att_emp" value="<?= h($att_emp) ?>">
          <input type="hidden" name="att_month" value="<?= h($att_month) ?>">
          <div class="filter-row">
            <div class="fg">
              <label>Date</label>
              <input type="date" name="report_date" class="form-control" value="<?= h($selected_date) ?>">
            </div>
            <div class="fg">
              <label>Employee</label>
              <select name="emp_id" class="form-select">
                <option value="all">All Employees</option>
                <?php foreach($employees as $e): ?>
                  <option value="<?= h($e['id']) ?>" <?= $selected_emp == $e['id'] ? 'selected' : '' ?>><?= h($e['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="fg" style="flex:2">
              <label>Search</label>
              <input type="text" name="search" class="form-control" placeholder="Search in reports..." value="<?= h($search) ?>">
            </div>
            <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Filter</button>
            <a href="?report_date=<?= h($selected_date) ?>&emp_id=<?= h($selected_emp) ?>&search=<?= urlencode($search) ?>&export=excel" class="btn-export">
              <i class="fas fa-file-excel"></i> Export
            </a>
          </div>
        </form>
      </div>
    </div>

    <!-- REPORTS -->
    <?php if (empty($reports)): ?>
      <div class="empty-state">
        <i class="fas fa-inbox"></i>
        <h5>No reports found</h5>
        <p>Try adjusting the date or employee filter</p>
      </div>
    <?php else: ?>
      <div class="reports-grid">
        <?php foreach($reports as $r):
          $photo = (!empty($r['photo']) && file_exists($upload_path.$r['photo'])) ? $upload_path.$r['photo'] : $upload_path."default.png";
          $status = $r['approval_status'] ?? 'Pending';
        ?>
        <div class="rcard s-<?= strtolower($status) ?>">
          <div class="rcard-head">
            <img src="<?= h($photo) ?>" class="rcard-avatar" alt="">
            <div class="rcard-emp">
              <div class="rcard-name"><?= h($r['emp_name']) ?></div>
              <div class="rcard-meta">
                <?php if(!empty($r['location_type'])): ?><span><i class="fas fa-map-marker-alt"></i><?= h($r['location_type']) ?></span><?php endif; ?>
                <?php if(!empty($r['client_name'])): ?><span><i class="fas fa-building"></i><?= h($r['client_name']) ?></span><?php endif; ?>
              </div>
            </div>
            <span class="status-pill sp-<?= $status ?>"><?= $status ?></span>
          </div>

          <div class="sec sec-morning"><div class="sec-lbl"><span class="dot"></span>Morning Plan</div><div class="sec-txt"><?= nl2br(h($r['Morning'] ?? '—')) ?></div></div>
          <div class="sec sec-hits"><div class="sec-lbl"><span class="dot"></span>Hits</div><div class="sec-txt"><?= nl2br(h($r['Hits'] ?? '—')) ?></div></div>
          <div class="sec sec-missed"><div class="sec-lbl"><span class="dot"></span>Missed</div><div class="sec-txt"><?= nl2br(h($r['Missed'] ?? '—')) ?></div></div>
          <div class="sec sec-carry"><div class="sec-lbl"><span class="dot"></span>Carry Forward</div><div class="sec-txt"><?= nl2br(h($r['carry forward'] ?? '—')) ?></div></div>
          <?php if(!empty($r['daily_summary'])): ?>
            <div class="sec sec-summary"><div class="sec-lbl"><span class="dot"></span>Daily Summary</div><div class="sec-txt"><?= nl2br(h($r['daily_summary'])) ?></div></div>
          <?php endif; ?>

          <div class="time-strip">
            <div class="time-box"><div class="time-box-lbl"><i class="fas fa-sign-in-alt"></i> Login</div><div class="time-box-val"><?= !empty($r['login_time']) ? date('h:i A', strtotime($r['login_time'])) : '—' ?></div></div>
            <div class="time-box"><div class="time-box-lbl"><i class="fas fa-sign-out-alt"></i> Logout</div><div class="time-box-val"><?= !empty($r['logout_time']) ? date('h:i A', strtotime($r['logout_time'])) : '—' ?></div></div>
          </div>

          <div class="media-strip">
            <?php if(!empty($r['latitude']) && !empty($r['longitude'])): ?>
              <a href="https://www.google.com/maps?q=<?= $r['latitude'] ?>,<?= $r['longitude'] ?>" target="_blank" class="media-btn"><i class="fas fa-map-pin"></i>Login Map</a>
            <?php else: ?><div class="media-btn no-data"><i class="fas fa-map-pin"></i>No Login Map</div><?php endif; ?>
            <?php if(!empty($r['logout_latitude']) && !empty($r['logout_longitude'])): ?>
              <a href="https://www.google.com/maps?q=<?= $r['logout_latitude'] ?>,<?= $r['logout_longitude'] ?>" target="_blank" class="media-btn"><i class="fas fa-map-marker-alt"></i>Logout Map</a>
            <?php else: ?><div class="media-btn no-data"><i class="fas fa-map-marker-alt"></i>No Logout Map</div><?php endif; ?>
            <?php if(!empty($r['photo_path']) && file_exists($r['photo_path'])): ?>
              <a href="<?= h($r['photo_path']) ?>" target="_blank" class="media-btn"><i class="fas fa-image"></i>View Photo</a>
            <?php else: ?><div class="media-btn no-data"><i class="fas fa-image"></i>No Photo</div><?php endif; ?>
          </div>

          <?php if($status === 'Pending'): ?>
            <div class="approval-area">
              <form method="POST">
                <input type="hidden" name="report_id" value="<?= $r['id'] ?>">
                <textarea name="manager_remark" class="remark-box" placeholder="Add a remark (optional)..."></textarea>
                <div class="action-row">
                  <button type="submit" name="action" value="approve" class="btn-approve"><i class="fas fa-check"></i> Approve</button>
                  <button type="submit" name="action" value="reject" class="btn-reject"><i class="fas fa-times"></i> Reject</button>
                </div>
              </form>
            </div>
          <?php else: ?>
            <div class="remark-display">
              <div class="remark-display-lbl">Manager Remark</div>
              <div class="remark-display-txt"><?= !empty($r['manager_remark']) ? nl2br(h($r['manager_remark'])) : '<em style="color:#cbd5e1">No remark added</em>' ?></div>
            </div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</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();
    });
  });
});
const toast = document.getElementById('toastEl');
if (toast) {
  setTimeout(() => { toast.style.transition='opacity .35s,transform .35s';toast.style.opacity='0';toast.style.transform='translateX(70px)'; }, 3200);
  setTimeout(() => toast.remove(), 3600);
}
</script>
</body>
</html>
<?php $conn->close(); ?>