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

/* ================= ACCESS CONTROL ================= */
$allowed_roles = ['superadmin', 'hr', 'md'];
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: login.php");
    exit();
}

$current_user_role = strtoupper($_SESSION['role']);
$current_user_name = $_SESSION['username'] ?? 'Admin';

/* ================= FILTERS ================= */
$selected_date       = $_GET['report_date'] ?? date('Y-m-d');
$selected_period     = $_GET['period']       ?? 'day';
$selected_div        = $_GET['division']     ?? 'all';
$selected_emp        = $_GET['emp_id']       ?? 'all';
$search_keyword      = $_GET['search']       ?? '';
$selected_month      = $_GET['report_month'] ?? date('Y-m');
$selected_year       = $_GET['report_year']  ?? date('Y');
$selected_from       = $_GET['date_from']    ?? '';
$selected_to         = $_GET['date_to']      ?? '';

/* ================= DIVISIONS ================= */
$div_stmt = $conn->query("
    SELECT DISTINCT division 
    FROM users 
    WHERE role = 'employee' 
      AND division IS NOT NULL 
      AND division != ''
    ORDER BY division ASC
");
$divisions = $div_stmt->fetch_all(MYSQLI_ASSOC);

/* ================= EMPLOYEES ================= */
$emp_query = "SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role = 'employee'";
$emp_params = [];
$emp_types  = "";

if ($selected_div !== 'all') {
    $emp_query .= " AND division = ?";
    $emp_params[] = $selected_div;
    $emp_types   .= "s";
}
$emp_query .= " ORDER BY first_name ASC";
$emp_stmt = $conn->prepare($emp_query);
if (!empty($emp_params)) {
    $emp_stmt->bind_param($emp_types, ...$emp_params);
}
$emp_stmt->execute();
$employees = $emp_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

/* ================= BUILD WHERE CLAUSE (reusable) ================= */
function buildWhere($selected_period, $selected_date, $selected_month, $selected_year, $selected_from, $selected_to, $selected_div, $selected_emp, $search_keyword) {
    $sql    = " WHERE 1=1";
    $params = [];
    $types  = "";

    if ($selected_period === 'day') {
        $sql .= " AND dr.report_date = ?";
        $params[] = $selected_date; $types .= "s";
    } elseif ($selected_period === 'month') {
        $sql .= " AND DATE_FORMAT(dr.report_date,'%Y-%m') = ?";
        $params[] = $selected_month; $types .= "s";
    } elseif ($selected_period === 'year') {
        $sql .= " AND YEAR(dr.report_date) = ?";
        $params[] = (int)$selected_year; $types .= "i";
    } elseif ($selected_period === 'range' && $selected_from && $selected_to) {
        $sql .= " AND dr.report_date BETWEEN ? AND ?";
        $params[] = $selected_from; $params[] = $selected_to; $types .= "ss";
    }

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

/* ================= EXPORT ================= */
if (isset($_GET['export'])) {
    [$where, $params, $types] = buildWhere($selected_period,$selected_date,$selected_month,$selected_year,$selected_from,$selected_to,$selected_div,$selected_emp,$search_keyword);

    $sql_export = "
    SELECT 
        dr.report_date,
        CONCAT(u.first_name,' ',u.last_name) AS emp_name,
        u.division,
        dr.location_type AS Location,
        dr.client_name,
        dr.Morning,
        dr.Hits,
        dr.Missed,
        dr.`carry forward`,
        dr.daily_summary,
        dr.manager_remark,
        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 . " ORDER BY dr.report_date DESC, dr.created_at DESC";

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

    $fname_suffix = $selected_period === 'day' ? $selected_date : ($selected_period === 'month' ? $selected_month : ($selected_period === 'year' ? $selected_year : "{$selected_from}_to_{$selected_to}"));

    if ($_GET['export'] == 'excel') {
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=daily_reports_{$fname_suffix}_div-{$selected_div}.xls");
        $headers = ["Date","Employee","Division","Location","Client Name","Morning","Hits","Missed","Carry Forward","Daily Summary","Manager Remark","Login Time","Logout Time","Photo Path","Latitude","Longitude","Logout Lat","Logout Lng","Status"];
        echo implode("\t", $headers) . "\n";
        while ($row = $result->fetch_assoc()) {
            echo ($row['report_date']??'')."\t".
                 ($row['emp_name']??'')."\t".($row['division']??'')."\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['manager_remark']??'')."\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;
    } elseif ($_GET['export'] == 'pdf') {
        require('fpdf/fpdf.php');
        $pdf = new FPDF('L','mm','A4');
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',8);
        $headers = ['Date','Employee','Division','Location','Client','Morning','Hits','Missed','Carry Fwd','Summary','Mgr Remark','Login','Logout','Status'];
        $widths  = [20,28,22,18,22,25,14,14,18,35,35,18,18,18];
        foreach($headers as $i=>$col) $pdf->Cell($widths[$i],8,$col,1);
        $pdf->Ln();
        $pdf->SetFont('Arial','',7);
        while($row = $result->fetch_assoc()){
            $pdf->Cell(20,8,substr($row['report_date']??'',0,12),1);
            $pdf->Cell(28,8,substr($row['emp_name']??'',0,22),1);
            $pdf->Cell(22,8,substr($row['division']??'',0,18),1);
            $pdf->Cell(18,8,substr($row['Location']??'',0,14),1);
            $pdf->Cell(22,8,substr($row['client_name']??'',0,18),1);
            $pdf->Cell(25,8,substr($row['Morning']??'',0,20),1);
            $pdf->Cell(14,8,$row['Hits']??'',1);
            $pdf->Cell(14,8,$row['Missed']??'',1);
            $pdf->Cell(18,8,substr($row['carry forward']??'',0,14),1);
            $pdf->Cell(35,8,substr($row['daily_summary']??'',0,30),1);
            $pdf->Cell(35,8,substr($row['manager_remark']??'',0,30),1);
            $pdf->Cell(18,8,substr($row['login_time']??'',0,14),1);
            $pdf->Cell(18,8,substr($row['logout_time']??'',0,14),1);
            $pdf->Cell(18,8,$row['approval_status']??'',1);
            $pdf->Ln();
        }
        $pdf->Output('D',"daily_reports_{$fname_suffix}_div-{$selected_div}.pdf");
        exit;
    }
}

/* ================= MAIN QUERY ================= */
[$where, $params, $types] = buildWhere($selected_period,$selected_date,$selected_month,$selected_year,$selected_from,$selected_to,$selected_div,$selected_emp,$search_keyword);

$sql = "
    SELECT dr.*, 
           CONCAT(u.first_name,' ',u.last_name) AS emp_name,
           u.division,
           u.photo AS photo
    FROM daily_reports dr
    JOIN users u ON dr.user_id = u.id
    " . $where . " ORDER BY dr.report_date DESC, dr.created_at DESC";

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

/* ================= STATS ================= */
$total   = count($reports);
$hits    = array_filter($reports, fn($r) => !empty($r['Hits']));
$missed  = array_filter($reports, fn($r) => !empty($r['Missed']));
$pending = array_filter($reports, fn($r) => ($r['approval_status'] ?? '') === 'pending');

/* Build export query string */
$exp_qs = http_build_query([
    'period' => $selected_period, 'report_date' => $selected_date,
    'report_month' => $selected_month, 'report_year' => $selected_year,
    'date_from' => $selected_from, 'date_to' => $selected_to,
    'division' => $selected_div, 'emp_id' => $selected_emp, 'search' => $search_keyword
]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Daily Reports Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">

<style>
:root{
    --ink:#0f172a;
    --ink2:#334155;
    --ink3:#64748b;
    --slate:#e2e8f0;
    --bg:#f0f4f8;
    --white:#ffffff;
    --primary:#1e40af;
    --primary-lt:#3b82f6;
    --accent:#f59e0b;
    --green:#10b981;
    --red:#ef4444;
    --yellow:#f59e0b;
    --radius:14px;
    --shadow:0 4px 24px rgba(15,23,42,.08);
    --shadow-md:0 8px 40px rgba(15,23,42,.12);
}

*{box-sizing:border-box;margin:0;padding:0}

body{
    background:var(--bg);
    font-family:'DM Sans',sans-serif;
    color:var(--ink);
    min-height:100vh;
}

/* ---- SIDEBAR ---- */
.sidebar{
    width:260px;
    background:var(--ink);
    color:#fff;
    position:fixed;
    top:0;bottom:0;left:0;
    padding:0;
    transform:translateX(-260px);
    transition:transform .35s cubic-bezier(.4,0,.2,1);
    z-index:1000;
    display:flex;flex-direction:column;
}
.sidebar.open{transform:translateX(0)}
.sidebar-brand{
    padding:28px 24px 20px;
    border-bottom:1px solid rgba(255,255,255,.08);
}
.sidebar-brand h4{
    font-family:'Syne',sans-serif;
    font-weight:800;
    font-size:1.25rem;
    letter-spacing:.5px;
    color:#fff;
}
.sidebar-brand p{font-size:.78rem;color:#94a3b8;margin-top:2px}
.sidebar-nav{padding:16px 12px;flex:1}
.sidebar-nav a{
    display:flex;align-items:center;gap:12px;
    color:#94a3b8;text-decoration:none;
    padding:11px 14px;border-radius:10px;
    font-size:.9rem;font-weight:500;
    margin-bottom:4px;
    transition:all .2s;
}
.sidebar-nav a:hover,.sidebar-nav a.active{
    background:rgba(255,255,255,.1);color:#fff;
    padding-left:18px;
}
.sidebar-nav a.danger{color:#f87171}
.sidebar-nav a.danger:hover{background:rgba(239,68,68,.15);color:#fca5a5}

/* ---- HAMBURGER ---- */
.hamburger{
    position:fixed;top:20px;left:20px;
    z-index:1100;
    background:var(--primary);color:#fff;
    border:none;width:44px;height:44px;
    border-radius:10px;
    display:flex;align-items:center;justify-content:center;
    box-shadow:0 4px 12px rgba(30,64,175,.35);
    cursor:pointer;transition:all .2s;
}
.hamburger:hover{transform:scale(1.07)}

/* ---- MAIN ---- */
.main{
    padding:32px 28px 60px;
    transition:margin-left .35s cubic-bezier(.4,0,.2,1);
}
.main.shifted{margin-left:260px}

/* ---- PAGE HEADER ---- */
.page-header{
    display:flex;align-items:center;justify-content:space-between;
    flex-wrap:wrap;gap:16px;
    margin-bottom:28px;
}
.page-title{
    font-family:'Syne',sans-serif;
    font-size:1.8rem;font-weight:800;
    color:var(--ink);
}
.page-title span{color:var(--primary-lt)}
.role-chip{
    display:inline-flex;align-items:center;gap:6px;
    background:var(--primary);color:#fff;
    padding:5px 14px;border-radius:50px;
    font-size:.78rem;font-weight:600;letter-spacing:.5px;
}

/* ---- STATS ---- */
.stats-row{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(160px,1fr));
    gap:16px;margin-bottom:28px;
}
.stat-card{
    background:var(--white);
    border-radius:var(--radius);
    padding:20px 22px;
    box-shadow:var(--shadow);
    display:flex;align-items:center;gap:14px;
    border-left:4px solid var(--primary);
    transition:transform .2s;
}
.stat-card:hover{transform:translateY(-3px)}
.stat-card.green{border-color:var(--green)}
.stat-card.red{border-color:var(--red)}
.stat-card.yellow{border-color:var(--yellow)}
.stat-icon{
    width:46px;height:46px;border-radius:10px;
    display:flex;align-items:center;justify-content:center;
    font-size:1.2rem;flex-shrink:0;
}
.stat-icon.blue{background:#eff6ff;color:var(--primary)}
.stat-icon.green{background:#ecfdf5;color:var(--green)}
.stat-icon.red{background:#fef2f2;color:var(--red)}
.stat-icon.yellow{background:#fffbeb;color:var(--yellow)}
.stat-val{
    font-family:'Syne',sans-serif;
    font-size:1.6rem;font-weight:800;line-height:1;
}
.stat-lbl{font-size:.78rem;color:var(--ink3);margin-top:3px}

/* ---- FILTER CARD ---- */
.filter-card{
    background:var(--white);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    padding:22px 24px;
    margin-bottom:28px;
}
.filter-card h6{
    font-family:'Syne',sans-serif;
    font-weight:700;font-size:.9rem;
    color:var(--ink2);margin-bottom:16px;
    display:flex;align-items:center;gap:8px;
}
.period-tabs{
    display:flex;gap:6px;flex-wrap:wrap;
    margin-bottom:18px;
}
.period-tab{
    padding:7px 18px;border-radius:50px;
    border:1.5px solid var(--slate);
    background:transparent;color:var(--ink3);
    font-size:.85rem;font-weight:500;
    cursor:pointer;transition:all .2s;
}
.period-tab:hover{border-color:var(--primary-lt);color:var(--primary)}
.period-tab.active{
    background:var(--primary);color:#fff;
    border-color:var(--primary);
    box-shadow:0 3px 10px rgba(30,64,175,.25);
}

.filter-section{display:none}
.filter-section.visible{display:block}

.form-label{font-size:.82rem;font-weight:600;color:var(--ink2);margin-bottom:5px}
.form-control,.form-select{
    border:1.5px solid var(--slate);
    border-radius:10px;font-size:.88rem;
    color:var(--ink);padding:9px 12px;
    transition:border-color .2s,box-shadow .2s;
}
.form-control:focus,.form-select:focus{
    border-color:var(--primary-lt);
    box-shadow:0 0 0 3px rgba(59,130,246,.12);
    outline:none;
}

.export-row{
    display:flex;flex-wrap:wrap;gap:10px;
    align-items:center;
    padding-top:16px;
    border-top:1px solid var(--slate);
    margin-top:16px;
}
.export-row span{font-size:.82rem;color:var(--ink3);font-weight:500}

/* ---- BUTTONS ---- */
.btn{
    display:inline-flex;align-items:center;gap:7px;
    padding:9px 18px;border-radius:10px;
    font-size:.86rem;font-weight:600;
    border:none;cursor:pointer;transition:all .2s;
    text-decoration:none;
}
.btn:hover{transform:translateY(-2px)}
.btn-primary{background:var(--primary);color:#fff;box-shadow:0 3px 10px rgba(30,64,175,.25)}
.btn-primary:hover{background:var(--primary-lt);color:#fff}
.btn-success{background:var(--green);color:#fff;box-shadow:0 3px 10px rgba(16,185,129,.25)}
.btn-success:hover{background:#059669;color:#fff}
.btn-danger{background:var(--red);color:#fff;box-shadow:0 3px 10px rgba(239,68,68,.25)}
.btn-danger:hover{background:#dc2626;color:#fff}
.btn-outline{background:transparent;color:var(--ink2);border:1.5px solid var(--slate)}
.btn-outline:hover{border-color:var(--primary-lt);color:var(--primary);background:#eff6ff}
.btn-sm{padding:6px 13px;font-size:.8rem}

/* ---- REPORT GRID ---- */
.reports-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill,minmax(340px,1fr));
    gap:20px;
}

.rcard{
    background:var(--white);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    overflow:hidden;
    transition:transform .25s,box-shadow .25s;
}
.rcard:hover{
    transform:translateY(-5px);
    box-shadow:var(--shadow-md);
}

.rcard-header{
    background:linear-gradient(135deg,#1e3a8a 0%,#2563eb 60%,#3b82f6 100%);
    padding:18px;
    display:flex;align-items:center;gap:14px;
    position:relative;overflow:hidden;
}
.rcard-header::after{
    content:'';position:absolute;
    top:-30px;right:-30px;
    width:100px;height:100px;
    background:rgba(255,255,255,.06);
    border-radius:50%;
}
.emp-avatar{
    width:52px;height:52px;border-radius:50%;
    object-fit:cover;
    border:3px solid rgba(255,255,255,.4);
    flex-shrink:0;
}
.emp-info{flex:1;min-width:0}
.emp-name{
    font-family:'Syne',sans-serif;
    font-weight:700;font-size:.95rem;
    color:#fff;white-space:nowrap;
    overflow:hidden;text-overflow:ellipsis;
}
.emp-meta{font-size:.76rem;color:rgba(255,255,255,.75);margin-top:3px}
.rdate-badge{
    background:rgba(255,255,255,.18);
    color:#fff;padding:4px 10px;
    border-radius:50px;font-size:.72rem;font-weight:600;
    white-space:nowrap;
}
.status-dot{
    width:8px;height:8px;border-radius:50%;
    display:inline-block;margin-right:4px;
    background:var(--green);
}
.status-dot.pending{background:var(--yellow)}
.status-dot.rejected{background:var(--red)}

.rcard-body{padding:0}

.rrow{
    display:flex;align-items:flex-start;
    border-bottom:1px solid #f1f5f9;
    padding:11px 16px;gap:12px;
}
.rrow:last-child{border-bottom:none}
.rrow-icon{
    width:28px;height:28px;border-radius:7px;
    display:flex;align-items:center;justify-content:center;
    font-size:.75rem;flex-shrink:0;margin-top:1px;
}
.rrow-icon.blue{background:#eff6ff;color:var(--primary)}
.rrow-icon.green{background:#ecfdf5;color:var(--green)}
.rrow-icon.red{background:#fef2f2;color:var(--red)}
.rrow-icon.yellow{background:#fffbeb;color:var(--yellow)}
.rrow-icon.purple{background:#f5f3ff;color:#7c3aed}
.rrow-icon.slate{background:#f8fafc;color:var(--ink3)}
.rrow-label{
    font-size:.72rem;font-weight:600;
    color:var(--ink3);text-transform:uppercase;
    letter-spacing:.5px;line-height:1;
    margin-bottom:3px;
}
.rrow-val{
    font-size:.875rem;color:var(--ink);
    white-space:pre-wrap;line-height:1.5;
}

.time-strip{
    display:flex;
    background:#f8fafc;
    border-top:1px solid var(--slate);
    padding:11px 16px;gap:16px;
}
.time-item{display:flex;align-items:center;gap:7px;font-size:.8rem}
.time-item i{color:var(--primary-lt)}
.time-item span{color:var(--ink2);font-weight:500}

.location-strip{
    display:flex;justify-content:center;gap:10px;
    padding:12px 16px;
    border-top:1px solid var(--slate);
    background:#f8fafc;
}
.loc-btn{
    display:inline-flex;align-items:center;gap:6px;
    padding:6px 14px;border-radius:50px;
    background:var(--primary);color:#fff;
    font-size:.78rem;font-weight:600;text-decoration:none;
    transition:all .2s;
}
.loc-btn:hover{background:var(--primary-lt);transform:scale(1.04)}
.loc-btn.out{background:#7c3aed}
.loc-btn.out:hover{background:#6d28d9}

.selfie-btn{
    display:inline-flex;align-items:center;gap:6px;
    padding:6px 14px;border-radius:50px;
    background:#fff;color:var(--primary);
    border:1.5px solid var(--primary);
    font-size:.78rem;font-weight:600;cursor:pointer;
    transition:all .2s;
}
.selfie-btn:hover{background:var(--primary);color:#fff}

.rcard-footer{
    padding:10px 16px;
    background:#fafafa;
    border-top:1px solid #f1f5f9;
    font-size:.73rem;color:var(--ink3);
    display:flex;justify-content:space-between;align-items:center;
}

/* ---- EMPTY STATE ---- */
.empty-state{
    text-align:center;padding:80px 20px;
    color:var(--ink3);
}
.empty-state i{font-size:3.5rem;margin-bottom:16px;opacity:.3}
.empty-state h5{font-family:'Syne',sans-serif;font-weight:700;font-size:1.1rem}
.empty-state p{font-size:.88rem;margin-top:6px}

/* ---- MODAL ---- */
.modal-content{border:none;border-radius:var(--radius);overflow:hidden}
.modal-header{
    background:linear-gradient(135deg,#1e3a8a,#3b82f6);
    color:#fff;border:none;
}
.modal-header .btn-close{filter:invert(1)}

/* ---- OVERLAY ---- */
.overlay{
    display:none;position:fixed;inset:0;
    background:rgba(0,0,0,.35);z-index:999;
    backdrop-filter:blur(2px);
}
.overlay.visible{display:block}

@media(max-width:768px){
    .main{padding:20px 16px 60px}
    .reports-grid{grid-template-columns:1fr}
    .stats-row{grid-template-columns:repeat(2,1fr)}
    .page-title{font-size:1.4rem}
    .main.shifted{margin-left:0}
}
</style>
</head>
<body>

<div class="overlay" id="overlay"></div>

<!-- ====== HAMBURGER ====== -->
<button class="hamburger" id="hamburgerBtn" aria-label="Toggle menu">
    <i class="fas fa-bars"></i>
</button>

<!-- ====== SIDEBAR ====== -->
<nav class="sidebar" id="sidebar">
    <div class="sidebar-brand">
        <h4>MPC Dashboard</h4>
        <p>Welcome, <?= htmlspecialchars($current_user_name) ?></p>
    </div>
    <div class="sidebar-nav">
        <a href="dashboard_md.php"><i class="fas fa-building fa-fw"></i> Organisation</a>
        <a href="payroll_md_dashboard.php"><i class="fas fa-money-check fa-fw"></i> Payroll</a>
        <a href="daily_reports_dashboard.php" class="active"><i class="fas fa-file-alt fa-fw"></i> Reports</a>
        <a href="mdmobile.php"><i class="fas fa-clock fa-fw"></i> Attendance</a>
        <a href="company_holidays.php"><i class="fas fa-calendar-alt fa-fw"></i> Holidays</a>
        <a href="logout.php" class="danger"><i class="fas fa-sign-out-alt fa-fw"></i> Logout</a>
    </div>
</nav>

<!-- ====== MAIN ====== -->
<main class="main" id="main">

<!-- Page Header -->
<div class="page-header">
    <div>
        <div class="page-title">Daily <span>Reports</span></div>
        <div style="font-size:.85rem;color:var(--ink3);margin-top:4px">
            View, filter and export employee daily reports
        </div>
    </div>
    <div class="d-flex align-items-center gap-2 flex-wrap">
        <span class="role-chip"><i class="fas fa-shield-halved"></i><?= $current_user_role ?></span>
        <a href="dashboard_md.php" class="btn btn-outline">
            <i class="fas fa-arrow-left"></i> Dashboard
        </a>
    </div>
</div>

<!-- Stats -->
<div class="stats-row">
    <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-file-lines"></i></div>
        <div><div class="stat-val"><?= $total ?></div><div class="stat-lbl">Total Reports</div></div>
    </div>
    <div class="stat-card green">
        <div class="stat-icon green"><i class="fas fa-circle-check"></i></div>
        <div><div class="stat-val"><?= count($hits) ?></div><div class="stat-lbl">With Hits</div></div>
    </div>
    <div class="stat-card red">
        <div class="stat-icon red"><i class="fas fa-circle-xmark"></i></div>
        <div><div class="stat-val"><?= count($missed) ?></div><div class="stat-lbl">With Missed</div></div>
    </div>
    <div class="stat-card yellow">
        <div class="stat-icon yellow"><i class="fas fa-clock"></i></div>
        <div><div class="stat-val"><?= count($pending) ?></div><div class="stat-lbl">Pending</div></div>
    </div>
</div>

<!-- ====== FILTER CARD ====== -->
<div class="filter-card">
    <h6><i class="fas fa-sliders" style="color:var(--primary)"></i> Filter Reports</h6>

    <form method="GET" id="filterForm">

        <!-- Period Tabs -->
        <div style="margin-bottom:6px;font-size:.82rem;font-weight:600;color:var(--ink2)">Select Period</div>
        <div class="period-tabs">
            <button type="button" class="period-tab <?= $selected_period==='day'?'active':'' ?>" data-period="day">
                <i class="fas fa-calendar-day"></i> Day
            </button>
            <button type="button" class="period-tab <?= $selected_period==='month'?'active':'' ?>" data-period="month">
                <i class="fas fa-calendar"></i> Month
            </button>
            <button type="button" class="period-tab <?= $selected_period==='year'?'active':'' ?>" data-period="year">
                <i class="fas fa-calendar-days"></i> Year
            </button>
            <button type="button" class="period-tab <?= $selected_period==='range'?'active':'' ?>" data-period="range">
                <i class="fas fa-calendar-week"></i> Date Range
            </button>
        </div>
        <input type="hidden" name="period" id="hiddenPeriod" value="<?= htmlspecialchars($selected_period) ?>">

        <!-- DAY -->
        <div class="filter-section <?= $selected_period==='day'?'visible':'' ?>" id="sec-day">
            <div class="row g-3">
                <div class="col-auto">
                    <label class="form-label">Date</label>
                    <input type="date" name="report_date" class="form-control" value="<?= htmlspecialchars($selected_date) ?>">
                </div>
            </div>
        </div>

        <!-- MONTH -->
        <div class="filter-section <?= $selected_period==='month'?'visible':'' ?>" id="sec-month">
            <div class="row g-3">
                <div class="col-auto">
                    <label class="form-label">Month</label>
                    <input type="month" name="report_month" class="form-control" value="<?= htmlspecialchars($selected_month) ?>">
                </div>
            </div>
        </div>

        <!-- YEAR -->
        <div class="filter-section <?= $selected_period==='year'?'visible':'' ?>" id="sec-year">
            <div class="row g-3">
                <div class="col-auto">
                    <label class="form-label">Year</label>
                    <select name="report_year" class="form-select" style="width:130px">
                        <?php for($y = date('Y'); $y >= 2020; $y--): ?>
                        <option value="<?= $y ?>" <?= $selected_year == $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- RANGE -->
        <div class="filter-section <?= $selected_period==='range'?'visible':'' ?>" id="sec-range">
            <div class="row g-3">
                <div class="col-auto">
                    <label class="form-label">From</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($selected_from) ?>">
                </div>
                <div class="col-auto">
                    <label class="form-label">To</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($selected_to) ?>">
                </div>
            </div>
        </div>

        <!-- Common Filters Row -->
        <div class="row g-3 mt-1">
            <div class="col-md-3 col-sm-6">
                <label class="form-label">Division</label>
                <select name="division" class="form-select" id="divSelect">
                    <option value="all">All Divisions</option>
                    <?php foreach($divisions as $d): ?>
                    <option value="<?= htmlspecialchars($d['division']) ?>" <?= $selected_div===$d['division']?'selected':'' ?>>
                        <?= htmlspecialchars($d['division']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 col-sm-6">
                <label class="form-label">Employee</label>
                <select name="emp_id" class="form-select">
                    <option value="all">All Employees</option>
                    <?php foreach($employees as $e): ?>
                    <option value="<?= $e['id'] ?>" <?= $selected_emp==$e['id']?'selected':'' ?>>
                        <?= htmlspecialchars($e['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 col-sm-6">
                <label class="form-label">Keyword Search</label>
                <div style="position:relative">
                    <input type="text" name="search" class="form-control" 
                           value="<?= htmlspecialchars($search_keyword) ?>" placeholder="Search reports...">
                    <i class="fas fa-search" style="position:absolute;right:12px;top:50%;transform:translateY(-50%);color:var(--ink3);font-size:.8rem"></i>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search"></i> Apply Filters
                </button>
            </div>
        </div>

        <!-- Export Row -->
        <div class="export-row">
            <span><i class="fas fa-download me-1"></i>Export filtered data:</span>
            <a href="?export=excel&<?= $exp_qs ?>" class="btn btn-success btn-sm">
                <i class="fas fa-file-excel"></i> Excel (.xls)
            </a>
            <a href="?export=pdf&<?= $exp_qs ?>" class="btn btn-danger btn-sm">
                <i class="fas fa-file-pdf"></i> PDF
            </a>
            <?php if($total > 0): ?>
            <span style="margin-left:auto;font-size:.8rem;color:var(--ink3)">
                <i class="fas fa-info-circle me-1"></i><?= $total ?> record<?= $total!==1?'s':'' ?> will be exported
            </span>
            <?php endif; ?>
        </div>

    </form>
</div>

<!-- ====== REPORT CARDS ====== -->
<?php if(empty($reports)): ?>
<div class="empty-state">
    <i class="fas fa-folder-open d-block"></i>
    <h5>No reports found</h5>
    <p>Try adjusting your filters or select a different date/period.</p>
</div>
<?php else: ?>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
    <div style="font-size:.85rem;color:var(--ink3)">
        Showing <strong style="color:var(--ink)"><?= $total ?></strong> report<?= $total!==1?'s':'' ?>
    </div>
</div>

<div class="reports-grid">
<?php foreach($reports as $r):
    $login_map  = ($r['latitude'] && $r['longitude']) ? "https://maps.google.com/?q={$r['latitude']},{$r['longitude']}" : "";
    $logout_map = ($r['logout_latitude'] && $r['logout_longitude']) ? "https://maps.google.com/?q={$r['logout_latitude']},{$r['logout_longitude']}" : "";
    $photo  = $r['photo'] ?: 'uploads/default-profile.png';
    $selfie = $r['photo_path'] ?: '';
    $status = strtolower($r['approval_status'] ?? 'pending');
    $status_class = $status === 'approved' ? '' : ($status === 'rejected' ? 'rejected' : 'pending');
?>
<div class="rcard">

    <div class="rcard-header">
        <img src="<?= htmlspecialchars($photo) ?>" class="emp-avatar" 
             onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($r['emp_name']) ?>&background=1e40af&color=fff&size=52'">
        <div class="emp-info">
            <div class="emp-name"><?= htmlspecialchars($r['emp_name']) ?></div>
            <div class="emp-meta">
                <?= htmlspecialchars($r['division'] ?: '—') ?> 
                <?php if($r['location_type']): ?>• <?= htmlspecialchars($r['location_type']) ?><?php endif; ?>
            </div>
            <div style="margin-top:5px">
                <span class="status-dot <?= $status_class ?>"></span>
                <span style="font-size:.74rem;color:rgba(255,255,255,.8);text-transform:capitalize"><?= htmlspecialchars($status) ?></span>
            </div>
        </div>
        <?php if($r['report_date']): ?>
        <div class="rdate-badge"><?= date('d M Y', strtotime($r['report_date'])) ?></div>
        <?php endif; ?>
    </div>

    <div class="rcard-body">

        <?php if($r['client_name']): ?>
        <div class="rrow">
            <div class="rrow-icon blue"><i class="fas fa-building"></i></div>
            <div><div class="rrow-label">Client</div><div class="rrow-val"><?= nl2br(htmlspecialchars($r['client_name'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['Morning']): ?>
        <div class="rrow">
            <div class="rrow-icon blue"><i class="fas fa-sun"></i></div>
            <div><div class="rrow-label">Morning Plan</div><div class="rrow-val"><?= nl2br(htmlspecialchars($r['Morning'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['Hits']): ?>
        <div class="rrow">
            <div class="rrow-icon green"><i class="fas fa-check-circle"></i></div>
            <div><div class="rrow-label">Hits</div><div class="rrow-val" style="color:#065f46"><?= nl2br(htmlspecialchars($r['Hits'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['Missed']): ?>
        <div class="rrow">
            <div class="rrow-icon red"><i class="fas fa-times-circle"></i></div>
            <div><div class="rrow-label">Missed</div><div class="rrow-val" style="color:#991b1b"><?= nl2br(htmlspecialchars($r['Missed'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['carry forward']): ?>
        <div class="rrow">
            <div class="rrow-icon yellow"><i class="fas fa-forward"></i></div>
            <div><div class="rrow-label">Carry Forward</div><div class="rrow-val" style="color:#854d0e"><?= nl2br(htmlspecialchars($r['carry forward'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['daily_summary']): ?>
        <div class="rrow">
            <div class="rrow-icon purple"><i class="fas fa-clipboard-list"></i></div>
            <div><div class="rrow-label">Daily Summary</div><div class="rrow-val"><?= nl2br(htmlspecialchars($r['daily_summary'])) ?></div></div>
        </div>
        <?php endif; ?>

        <?php if($r['manager_remark']): ?>
        <div class="rrow">
            <div class="rrow-icon slate"><i class="fas fa-comment-dots"></i></div>
            <div><div class="rrow-label">Manager Remark</div><div class="rrow-val"><?= nl2br(htmlspecialchars($r['manager_remark'])) ?></div></div>
        </div>
        <?php endif; ?>

        <div class="time-strip">
            <div class="time-item">
                <i class="fas fa-right-to-bracket"></i>
                <div>
                    <div style="font-size:.7rem;color:var(--ink3)">Login</div>
                    <span><?= htmlspecialchars($r['login_time'] ?? '—') ?></span>
                </div>
            </div>
            <div class="time-item" style="margin-left:auto">
                <i class="fas fa-right-from-bracket"></i>
                <div>
                    <div style="font-size:.7rem;color:var(--ink3)">Logout</div>
                    <span><?= htmlspecialchars($r['logout_time'] ?? '—') ?></span>
                </div>
            </div>
        </div>

        <?php if($login_map || $logout_map || $selfie): ?>
        <div class="location-strip">
            <?php if($login_map): ?>
            <a href="<?= $login_map ?>" target="_blank" class="loc-btn">
                <i class="fas fa-map-marker-alt"></i> Login Loc
            </a>
            <?php endif; ?>
            <?php if($logout_map): ?>
            <a href="<?= $logout_map ?>" target="_blank" class="loc-btn out">
                <i class="fas fa-map-marker-alt"></i> Logout Loc
            </a>
            <?php endif; ?>
            <?php if($selfie): ?>
            <button type="button" class="selfie-btn"
                    data-bs-toggle="modal" data-bs-target="#selfieModal"
                    data-selfie-src="<?= htmlspecialchars($selfie) ?>"
                    data-emp-name="<?= htmlspecialchars($r['emp_name']) ?>">
                <i class="fas fa-camera"></i> Selfie
            </button>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    </div>

    <div class="rcard-footer">
        <span><i class="fas fa-clock me-1"></i>Submitted: <?= date('d M Y h:i A', strtotime($r['created_at'])) ?></span>
        <span class="rdate-badge" style="background:var(--slate);color:var(--ink2)"><?= htmlspecialchars(ucfirst($status)) ?></span>
    </div>

</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

</main>

<!-- ====== SELFIE MODAL ====== -->
<div class="modal fade" id="selfieModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-camera me-2"></i><span id="modalEmpName">Selfie</span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center p-3">
                <img id="modalSelfieImg" src="" alt="Selfie" 
                     style="max-width:100%;border-radius:10px;box-shadow:0 4px 20px rgba(0,0,0,.15)">
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// ----- Sidebar -----
const hamburger = document.getElementById('hamburgerBtn');
const sidebar   = document.getElementById('sidebar');
const mainEl    = document.getElementById('main');
const overlay   = document.getElementById('overlay');

function toggleSidebar(force) {
    const open = force !== undefined ? force : !sidebar.classList.contains('open');
    sidebar.classList.toggle('open', open);
    mainEl.classList.toggle('shifted', open);
    overlay.classList.toggle('visible', open);
    hamburger.innerHTML = open ? '<i class="fas fa-times"></i>' : '<i class="fas fa-bars"></i>';
}
hamburger.addEventListener('click', () => toggleSidebar());
overlay.addEventListener('click', () => toggleSidebar(false));

// ----- Period Tabs -----
const tabs        = document.querySelectorAll('.period-tab');
const hiddenPeriod = document.getElementById('hiddenPeriod');
const sections    = { day:'sec-day', month:'sec-month', year:'sec-year', range:'sec-range' };

function showPeriod(period) {
    tabs.forEach(t => t.classList.toggle('active', t.dataset.period === period));
    hiddenPeriod.value = period;
    Object.entries(sections).forEach(([key, id]) => {
        document.getElementById(id).classList.toggle('visible', key === period);
    });
}

tabs.forEach(tab => {
    tab.addEventListener('click', () => showPeriod(tab.dataset.period));
});

// ----- Division change reloads employee list -----
document.getElementById('divSelect').addEventListener('change', function() {
    const url = new URL(window.location);
    url.searchParams.set('division', this.value);
    url.searchParams.set('period', hiddenPeriod.value);
    url.searchParams.delete('emp_id');
    window.location = url.toString();
});

// ----- Selfie Modal -----
document.getElementById('selfieModal').addEventListener('show.bs.modal', event => {
    const btn = event.relatedTarget;
    document.getElementById('modalSelfieImg').src = btn.getAttribute('data-selfie-src');
    document.getElementById('modalEmpName').textContent = (btn.getAttribute('data-emp-name') || '') + ' — Selfie';
});
</script>
</body>
</html>
<?php $conn->close(); ?>