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

$role = strtolower($_SESSION['role'] ?? '');

if (!isset($_SESSION['username']) || !in_array($role, ['admin','superadmin','manager','md'])) {
    header("Location: index.php");
    exit;
}

$is_admin = in_array($role, ['admin','superadmin']);
$message  = '';

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

/* ================= OFFICE TIMING CONFIG ================= */
/* Office hours: 09:30 - 18:30. Grace period until 09:40.
   Login after 09:30            -> Late
   Logout between 13:00-17:00   -> Half Day
   Logout between 17:00-18:00   -> Permission
   Logout at/after 18:00        -> Full attendance
*/
define('OFFICE_IN',        '09:30:00');
define('LATE_GRACE_UNTIL', '09:30:00');
define('OFFICE_OUT',       '18:30:00');
define('HALFDAY_FROM',     '13:00:00');
define('HALFDAY_TO',       '17:00:00');
define('PERMISSION_FROM',  '17:00:00');
define('PERMISSION_TO',    '18:00:00');

/**
 * Classify a single day's attendance based on login/logout datetimes.
 * Returns an array with status code, label, badge css class, and worked hours.
 */
function classifyAttendance($login_time, $logout_time) {
    $out = [
        'code'         => 'present',
        'label'        => 'Present',
        'class'        => 'tag-ok',
        'hours'        => null,
        'is_late'      => false,
        'no_checkout'  => false,
        'login_disp'   => $login_time  ? date('h:i A', strtotime($login_time))  : '',
        'logout_disp'  => $logout_time ? date('h:i A', strtotime($logout_time)) : '',
    ];

    if (empty($login_time)) {
        $out['code']  = 'absent';
        $out['label'] = 'Absent';
        $out['class'] = 'tag-bad';
        return $out;
    }

    $login_ts  = strtotime($login_time);
    $login_hm  = date('H:i:s', $login_ts);
    $is_late   = $login_hm > LATE_GRACE_UNTIL;
    $out['is_late'] = $is_late;

    /* Logged in but never checked out */
    if (empty($logout_time)) {
        $out['no_checkout'] = true;
        $out['code']  = 'no_checkout';
        $out['label'] = $is_late ? 'Late · No Checkout' : 'No Checkout';
        $out['class'] = 'tag-bad';
        return $out;
    }

    $logout_ts = strtotime($logout_time);
    $logout_hm = date('H:i:s', $logout_ts);
    $diff_secs = $logout_ts - $login_ts;
    if ($diff_secs > 0 && $diff_secs < 16 * 3600) {
        $out['hours'] = round($diff_secs / 3600, 2);
    }

    if ($logout_hm >= HALFDAY_FROM && $logout_hm < HALFDAY_TO) {
        $out['code']  = 'half_day';
        $out['label'] = 'Half Day';
        $out['class'] = 'tag-bad';
        return $out;
    }
    if ($logout_hm >= PERMISSION_FROM && $logout_hm < PERMISSION_TO) {
        $out['code']  = 'permission';
        $out['label'] = 'Permission';
        $out['class'] = 'tag-warn';
        return $out;
    }

    if ($is_late) {
        $out['code']  = 'late';
        $out['label'] = 'Late';
        $out['class'] = 'tag-warn';
        return $out;
    }

    return $out;
}

/* ================= UPDATE REPORT (POST) ================= */
/* Admin/superadmin can update login time, logout time, manager remark and
   approval status for a single daily_reports row. Uses POST + redirect
   (PRG pattern) so the filtered view is preserved and refresh-resubmit is avoided. */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_report'])) {
    $upd_id     = (int)($_POST['report_id'] ?? 0);
    $upd_login  = trim($_POST['login_time'] ?? '');
    $upd_logout = trim($_POST['logout_time'] ?? '');
    $upd_remark = trim($_POST['manager_remark'] ?? '');
    $upd_status = trim($_POST['approval_status'] ?? 'pending');

    if ($upd_id > 0 && $is_admin) {
        $upd_login_val  = $upd_login  !== '' ? $upd_login  : null;
        $upd_logout_val = $upd_logout !== '' ? $upd_logout : null;
        $upd_stmt = $conn->prepare("UPDATE daily_reports SET login_time=?, logout_time=?, manager_remark=?, approval_status=? WHERE id=?");
        $upd_stmt->bind_param("ssssi", $upd_login_val, $upd_logout_val, $upd_remark, $upd_status, $upd_id);
        $upd_stmt->execute();
    }

    $qsArr = $_GET;
    $qsArr['updated'] = 1;
    header("Location: daily_reports_dashboard.php?" . http_build_query($qsArr));
    exit;
}

/* ================= WEEKEND / WORK-DAYS CONFIG ================= */
if (isset($_GET['sat_work'])) $_SESSION['sat_work'] = (int)$_GET['sat_work'];
if (isset($_GET['sun_work'])) $_SESSION['sun_work'] = (int)$_GET['sun_work'];
$sat_work = (int)($_SESSION['sat_work'] ?? 0);
$sun_work = (int)($_SESSION['sun_work'] ?? 0);

/* ================= FILTERS ================= */
$selected_date   = $_GET['report_date']  ?? date('Y-m-d');
$selected_period = $_GET['period']       ?? 'day';
$selected_div    = $_GET['division']     ?? 'all';
$selected_loc    = $_GET['location']     ?? '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']      ?? '';

/* ================= RESOLVE DATE RANGE ================= */
function resolveDateRange($period, $date, $month, $year, $from, $to) {
    if ($period === 'day')   return [$date, $date];
    if ($period === 'month') return [date('Y-m-01', strtotime($month . '-01')), date('Y-m-t', strtotime($month . '-01'))];
    if ($period === 'year')  return [$year . '-01-01', $year . '-12-31'];
    if ($period === 'range' && $from && $to) return [$from, $to];
    return [date('Y-m-d'), date('Y-m-d')];
}
[$range_from, $range_to] = resolveDateRange($selected_period, $selected_date, $selected_month, $selected_year, $selected_from, $selected_to);

/* ================= HOLIDAYS IN RANGE ================= */
$holiday_stmt = $conn->prepare("
    SELECT holiday_date, name 
    FROM company_holidays 
    WHERE holiday_date BETWEEN ? AND ?
    ORDER BY holiday_date ASC
");
$holiday_stmt->bind_param("ss", $range_from, $range_to);
$holiday_stmt->execute();
$holidays_raw  = $holiday_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$holiday_dates = array_column($holidays_raw, 'holiday_date');

/* ================= CALCULATE WORKING DAYS ================= */
function calcWorkingDays($from, $to, $sat_work, $sun_work, $holiday_dates) {
    $count = 0;
    $cur   = strtotime($from);
    $end   = strtotime($to);
    while ($cur <= $end) {
        $dow   = (int)date('w', $cur);
        $dstr  = date('Y-m-d', $cur);
        $isWknd = ($dow === 0 && !$sun_work) || ($dow === 6 && !$sat_work);
        if (!$isWknd && !in_array($dstr, $holiday_dates)) $count++;
        $cur = strtotime('+1 day', $cur);
    }
    return $count;
}
$working_days = calcWorkingDays($range_from, $range_to, $sat_work, $sun_work, $holiday_dates);

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

/* ================= LOCATIONS ================= */
/* Employee location resolved from users.work_location, falling back to users.location */
$loc_stmt = $conn->query("
    SELECT DISTINCT COALESCE(NULLIF(work_location,''), NULLIF(location,'')) AS loc
    FROM users
    WHERE role IN ('employee','manager')
      AND COALESCE(NULLIF(work_location,''), NULLIF(location,'')) IS NOT NULL
    ORDER BY loc ASC
");
$locations = $loc_stmt->fetch_all(MYSQLI_ASSOC);

/* ================= TOTAL EMPLOYEES ================= */
$emp_count_query  = "SELECT COUNT(*) AS cnt 
                     FROM users 
                     WHERE role IN ('employee','manager') 
                     AND status = 'active'";
$emp_count_params = []; $emp_count_types = "";
if ($selected_div !== 'all') { $emp_count_query .= " AND division=?"; $emp_count_params[] = $selected_div; $emp_count_types .= "s"; }
if ($selected_loc !== 'all') { $emp_count_query .= " AND COALESCE(NULLIF(work_location,''),NULLIF(location,''))=?"; $emp_count_params[] = $selected_loc; $emp_count_types .= "s"; }
$ec_stmt = $conn->prepare($emp_count_query);
if (!empty($emp_count_params)) $ec_stmt->bind_param($emp_count_types, ...$emp_count_params);
$ec_stmt->execute();
$total_employees = (int)$ec_stmt->get_result()->fetch_assoc()['cnt'];

/* ================= EMPLOYEES DROPDOWN ================= */
$emp_query  = "SELECT id, CONCAT(first_name,' ',last_name) AS name 
               FROM users 
               WHERE role IN ('employee','manager') 
               AND status = 'active'";
$emp_params = []; $emp_types = "";
if ($selected_div !== 'all') { $emp_query .= " AND division=?"; $emp_params[] = $selected_div; $emp_types .= "s"; }
if ($selected_loc !== 'all') { $emp_query .= " AND COALESCE(NULLIF(work_location,''),NULLIF(location,''))=?"; $emp_params[] = $selected_loc; $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);

/* ================= LEAVES IN RANGE (from leave_requests table) ================= */
/* Table 2 in the spec: employee_id, start_date, end_date, leave_type, status, hr_status,
   permission_hours, permission_date, permission_time_from, permission_time_to */
$leave_stmt = $conn->prepare("
    SELECT employee_id, start_date, end_date, leave_type, status, hr_status,
           permission_hours, permission_date, permission_time_from, permission_time_to
    FROM leave_requests
    WHERE status = 'Approved'
      AND (
            (start_date IS NOT NULL AND end_date IS NOT NULL AND start_date <= ? AND end_date >= ?)
            OR (permission_date BETWEEN ? AND ?)
          )
");
$leave_stmt->bind_param("ssss", $range_to, $range_from, $range_from, $range_to);
$leave_stmt->execute();
$leaves_raw = $leave_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

/* Build a quick lookup: leave_map[employee_id][Y-m-d] = leave_type ('CL','PL','SL', etc. or 'Permission') */
$leave_map = [];
foreach ($leaves_raw as $lv) {
    $eid = $lv['employee_id'];
    if (!empty($lv['start_date']) && !empty($lv['end_date']) && $lv['leave_type'] !== 'Permission') {
        $cur = strtotime($lv['start_date']);
        $end = strtotime($lv['end_date']);
        while ($cur <= $end) {
            $d = date('Y-m-d', $cur);
            if ($d >= $range_from && $d <= $range_to) {
                $leave_map[$eid][$d] = $lv['leave_type'] ?: 'Leave';
            }
            $cur = strtotime('+1 day', $cur);
        }
    } elseif (!empty($lv['permission_date'])) {
        $d = $lv['permission_date'];
        if ($d >= $range_from && $d <= $range_to) {
            $leave_map[$eid][$d] = 'Permission';
        }
    }
}

/* ================= BUILD WHERE CLAUSE ================= */
function buildWhere($period,$date,$month,$year,$from,$to,$div,$emp,$keyword,$loc='all') {
    $sql=""; $p=[]; $t="";
    if ($period==='day')                     { $sql.=" AND dr.report_date=?";                                $p[]=$date;      $t.="s"; }
    elseif ($period==='month')               { $sql.=" AND DATE_FORMAT(dr.report_date,'%Y-%m')=?";          $p[]=$month;     $t.="s"; }
    elseif ($period==='year')                { $sql.=" AND YEAR(dr.report_date)=?";                         $p[]=(int)$year; $t.="i"; }
    elseif ($period==='range'&&$from&&$to)   { $sql.=" AND dr.report_date BETWEEN ? AND ?";                 $p[]=$from; $p[]=$to; $t.="ss"; }
    if ($div!=='all') { $sql.=" AND u.division=?"; $p[]=$div; $t.="s"; }
    if ($emp!=='all') { $sql.=" AND dr.user_id=?"; $p[]=$emp; $t.="i"; }
    if ($loc!=='all' && $loc!=='') { $sql.=" AND COALESCE(NULLIF(u.work_location,''),NULLIF(u.location,''))=?"; $p[]=$loc; $t.="s"; }
    if (!empty($keyword)) {
        $like="%$keyword%";
        $sql.=" AND (dr.Morning LIKE ? OR dr.Hits LIKE ? OR dr.Missed LIKE ? OR dr.`carry forward` LIKE ? OR dr.daily_summary LIKE ?)";
        $p=array_merge($p,[$like,$like,$like,$like,$like]); $t.="sssss";
    }
    return [" WHERE 1=1".$sql, $p, $t];
}

/* ================= 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,$selected_loc);
    $sql_export = "SELECT dr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name, u.id AS emp_id, u.division,
    COALESCE(NULLIF(u.work_location,''), NULLIF(u.location,'')) AS emp_location, dr.location_type AS Location
    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();
    $sfx = $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_{$sfx}_div-{$selected_div}.xls");
        $hdr = ["Date","Emp ID","Employee","Division","Employee Location","Location","Client Name","Morning","Hits","Missed","Carry Forward","Daily Summary","Manager Remark","Login","Logout","Hours Worked","Attendance Status","Status"];
        echo implode("\t",$hdr)."\n";
        while ($row=$result->fetch_assoc()) {
            $att = classifyAttendance($row['login_time'] ?? null, $row['logout_time'] ?? null);
            echo ($row['report_date']??'')."\t".($row['emp_id']??'')."\t".($row['emp_name']??'')."\t".($row['division']??'')."\t".($row['emp_location']??'')."\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".($att['hours']!==null?$att['hours']:'')."\t".($att['label'])."\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',7);
        $hdrs=['Date','Emp ID','Employee','Division','Emp Loc','Location','Client','Morning','Hits','Missed','Carry Fwd','Summary','Remark','Login','Logout','Hours','Att.','Status'];
        $widths=[15,12,22,16,15,13,16,18,11,11,13,24,20,13,13,10,15,13];
        foreach($hdrs as $i=>$c) $pdf->Cell($widths[$i],8,$c,1); $pdf->Ln();
        $pdf->SetFont('Arial','',6.5);
        while($row=$result->fetch_assoc()){
            $att = classifyAttendance($row['login_time'] ?? null, $row['logout_time'] ?? null);
            $row['_hours']  = $att['hours']!==null ? $att['hours'] : '';
            $row['_status'] = $att['label'];
            foreach(['report_date','emp_id','emp_name','division','emp_location','Location','client_name','Morning','Hits','Missed','carry forward','daily_summary','manager_remark','login_time','logout_time','_hours','_status','approval_status'] as $i=>$k)
                $pdf->Cell($widths[$i],8,substr($row[$k]??'',0,intval($widths[$i]/3)+4),1);
            $pdf->Ln();
        }
        $pdf->Output('D',"daily_reports_{$sfx}.pdf"); exit;
    } elseif ($_GET['export']==='matrix') {
        /* ===== MONTHLY ATTENDANCE MATRIX EXPORT ===== */
        /* Codes: P=Present  LT=Late  HD=Half Day  Per=Permission  NC=No Checkout
                  A=Absent   WO=Weekly Off  H=Holiday  CO=Comp-off  (or leave type e.g. CL/SL) */
        $m_from = $range_from; $m_to = $range_to;
        $days_in_range = [];
        $cur = strtotime($m_from); $end = strtotime($m_to);
        while ($cur <= $end) { $days_in_range[] = date('Y-m-d', $cur); $cur = strtotime('+1 day', $cur); }

        $all_emp_q = "SELECT id, CONCAT(first_name,' ',last_name) AS name, division, role,
                      COALESCE(NULLIF(work_location,''), NULLIF(location,'')) AS emp_location
                      FROM users 
                      WHERE role IN ('employee','manager') 
                      AND status = 'active'";
        $all_emp_p = []; $all_emp_t = "";
        if ($selected_div !== 'all') { $all_emp_q .= " AND division=?"; $all_emp_p[] = $selected_div; $all_emp_t .= "s"; }
        if ($selected_loc !== 'all') { $all_emp_q .= " AND COALESCE(NULLIF(work_location,''),NULLIF(location,''))=?"; $all_emp_p[] = $selected_loc; $all_emp_t .= "s"; }
        if ($selected_emp !== 'all') { $all_emp_q .= " AND id=?"; $all_emp_p[] = $selected_emp; $all_emp_t .= "i"; }
        $all_emp_q .= " ORDER BY name ASC";
        $aes = $conn->prepare($all_emp_q);
        if (!empty($all_emp_p)) $aes->bind_param($all_emp_t, ...$all_emp_p);
        $aes->execute();
        $matrix_emps = $aes->get_result()->fetch_all(MYSQLI_ASSOC);

        /* login/logout per employee per date for this range */
        $mx_stmt = $conn->prepare("SELECT dr.user_id, dr.report_date, dr.login_time, dr.logout_time FROM daily_reports dr JOIN users u ON dr.user_id=u.id AND u.status = 'active' WHERE dr.report_date BETWEEN ? AND ?");
        $mx_stmt->bind_param("ss", $m_from, $m_to);
        $mx_stmt->execute();
        $mx_rows = $mx_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $mx_map = [];
        foreach ($mx_rows as $mr) { $mx_map[$mr['user_id']][$mr['report_date']] = $mr; }

        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=attendance_matrix_{$sfx}.xls");

        /* Header row: Name, Emp ID, Role, Location, then each day spans 4 sub-columns (In / Out / Hrs / Status) */
        echo "Name\tEmp ID\tRole\tLocation\t";
        foreach ($days_in_range as $d) echo date('j-M', strtotime($d))."\t\t\t\t";
        echo "No of days present\tabsent\tLeave\thalf day\tpermission\tno checkout\tholidays\tcomoff\tTotal working days\tTotal hours worked\tLOP\n";

        echo "\t\t\t\t";
        foreach ($days_in_range as $d) echo "In\tOut\tHrs\tStatus\t";
        echo "\n";

        foreach ($matrix_emps as $me) {
            $uid = $me['id'];
            echo $me['name']."\t".$me['id']."\t".ucfirst($me['role'])."\t".($me['emp_location'] ?: '-')."\t";
            $present=0; $absent=0; $leave=0; $halfday=0; $perm=0; $holcount=0; $comoff=0; $nocheckout=0; $total_hours=0;
            foreach ($days_in_range as $d) {
                $dow = (int)date('w', strtotime($d));
                $is_weekend = ($dow===0 && !$sun_work) || ($dow===6 && !$sat_work);
                $is_holiday = in_array($d, $holiday_dates);
                $in_t = ''; $out_t = ''; $hrs = ''; $code = '';

                if ($is_holiday) { $code='H'; $holcount++; }
                elseif ($is_weekend) { $code='WO'; }
                elseif (isset($leave_map[$uid][$d])) {
                    $lt = $leave_map[$uid][$d];
                    if ($lt === 'Permission') { $code='Per'; $perm++; }
                    elseif ($lt === 'Compensatory') { $code='CO'; $comoff++; }
                    else { $code = $lt; $leave++; }
                } elseif (isset($mx_map[$uid][$d])) {
                    $rowd = $mx_map[$uid][$d];
                    $att  = classifyAttendance($rowd['login_time'] ?? null, $rowd['logout_time'] ?? null);
                    $in_t  = $att['login_disp'];
                    $out_t = $att['logout_disp'];
                    $hrs   = $att['hours'] !== null ? $att['hours'] : '';
                    if ($att['hours'] !== null) $total_hours += $att['hours'];

                    if ($att['code']==='no_checkout') { $code = $att['is_late'] ? 'LT/NC' : 'NC'; $nocheckout++; $present++; }
                    elseif ($att['code']==='half_day') { $code='HD'; $halfday++; $present++; }
                    elseif ($att['code']==='permission') { $code='Per'; $perm++; $present++; }
                    elseif ($att['code']==='late') { $code='LT'; $present++; }
                    else { $code='P'; $present++; }
                } else {
                    $code='A'; $absent++;
                }
                echo "$in_t\t$out_t\t$hrs\t$code\t";
            }
            $twd = $working_days;
            $lop = max(0, $twd - $present - $leave - $comoff);
            $total_hours = round($total_hours, 2);
            echo "$present\t$absent\t$leave\t$halfday\t$perm\t$nocheckout\t$holcount\t$comoff\t$twd\t$total_hours\t$lop\n";
        }
        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,$selected_loc);
$sql = "SELECT dr.*, CONCAT(u.first_name,' ',u.last_name) AS emp_name, u.id AS emp_id, u.division, u.photo,
        COALESCE(NULLIF(u.work_location,''), NULLIF(u.location,'')) AS emp_location
        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);

/* ================= ATTENDANCE 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');
$approved = array_filter($reports, fn($r)=>($r['approval_status']??'')==='approved');
$rejected = array_filter($reports, fn($r)=>($r['approval_status']??'')==='rejected');

/* Attach attendance classification + leave flag to each report row */
foreach ($reports as &$r) {
    $r['_att']       = classifyAttendance($r['login_time'] ?? null, $r['logout_time'] ?? null);
    $r['_on_leave']  = isset($leave_map[$r['user_id']][$r['report_date']]) ? $leave_map[$r['user_id']][$r['report_date']] : null;
}
unset($r);

$late_reports       = array_filter($reports, fn($r)=>$r['_att']['code']==='late');
$nocheckout_reports = array_filter($reports, fn($r)=>$r['_att']['no_checkout']);
$halfday_reports    = array_filter($reports, fn($r)=>$r['_att']['code']==='half_day');
$permission_reports = array_filter($reports, fn($r)=>$r['_att']['code']==='permission');
$leave_reports_today = array_filter($reports, fn($r)=>!empty($r['_on_leave']));

$present_emp_ids = array_unique(array_column($reports,'user_id'));
$present_count   = count($present_emp_ids);

/* Employees on approved leave for the whole selected range (for absent/leave split) */
$emp_on_leave_ids = array_keys($leave_map);
$emp_on_leave_ids = array_intersect($emp_on_leave_ids, array_column($employees, 'id'));
$on_leave_count   = count(array_diff($emp_on_leave_ids, $present_emp_ids));

$absent_count = max(0, $total_employees - $present_count - $on_leave_count);

$expected_submissions = $working_days * ($selected_emp === 'all' ? $total_employees : 1);
$attendance_pct = $expected_submissions > 0 ? round(($total / $expected_submissions) * 100) : 0;

/* ================= PER-EMPLOYEE PRESENT/ABSENT DAYS ================= */
$emp_present_days = [];
foreach ($reports as $r) {
    $uid  = $r['user_id'];
    $rdate = $r['report_date'];
    if (!isset($emp_present_days[$uid])) $emp_present_days[$uid] = [];
    if (!in_array($rdate, $emp_present_days[$uid])) $emp_present_days[$uid][] = $rdate;
}

/* ================= PAYROLL QUERY STRING ================= */
$payroll_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,
    'location'     => $selected_loc,
    'emp_id'       => $selected_emp,
    'working_days' => $working_days,
    'present'      => $present_count,
    'absent'       => $absent_count,
]);

$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,'location'=>$selected_loc,'emp_id'=>$selected_emp,'search'=>$search_keyword
]);

/* ================= GROUP REPORTS BY EMPLOYEE ================= */
$emp_summary = [];
foreach ($reports as $r) {
    $uid = $r['user_id'];
    if (!isset($emp_summary[$uid])) {
        $emp_summary[$uid] = [
            'name'     => $r['emp_name'],
            'division' => $r['division'],
            'photo'    => $r['photo'] ?? '',
            'days'     => [],
        ];
    }
    if (!in_array($r['report_date'], $emp_summary[$uid]['days'])) {
        $emp_summary[$uid]['days'][] = $r['report_date'];
    }
}

function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
$username_session = $_SESSION['username'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.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=Sora:wght@300;400;500;600;700&family=JetBrains+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">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;
  --radius:     12px;
  --radius-lg:  18px;
  --shadow:     0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  --shadow-md:  0 4px 8px rgba(15,23,42,.08), 0 12px 40px rgba(15,23,42,.10);
  --primary:    #1d4ed8;
  --primary-lt: #3b82f6;
  --primary-bg: #eff6ff;
  --green:      #059669;
  --green-bg:   #ecfdf5;
  --red:        #dc2626;
  --red-bg:     #fef2f2;
  --amber:      #d97706;
  --amber-bg:   #fffbeb;
  --violet:     #7c3aed;
  --violet-bg:  #f5f3ff;
  --cyan:       #0891b2;
  --cyan-bg:    #ecfeff;
  --pink:       #db2777;
  --pink-bg:    #fdf2f8;
  font-family: 'Sora', system-ui, sans-serif;
}

html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

.layout { display: flex; min-height: 100vh; }

/* ── SIDEBAR ── */
.sidebar {
  width: var(--sidebar-w); background: var(--sidebar-bg);
  position: fixed; inset: 0 auto 0 0; z-index: 200;
  display: flex; flex-direction: column;
  overflow-y: auto; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item { list-style: none; }
.nav-link, .nav-dropdown-toggle {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  cursor: pointer; border: none; background: none; width: 100%; text-align: left;
  transition: background .15s, color .15s;
}
.nav-link:hover, .nav-dropdown-toggle:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i, .nav-dropdown-toggle i { width: 16px; text-align: center; font-size: 13px; }
.nav-dropdown-toggle .arrow { margin-left: auto; transition: transform .2s; font-size: 10px; }
.nav-dropdown-toggle.open .arrow { transform: rotate(180deg); }
.nav-submenu { list-style:none; overflow:hidden; max-height:0; transition:max-height .3s ease; padding-left:26px; }
.nav-submenu.open { max-height: 600px; }
.nav-submenu .nav-link { font-size: 12px; padding: 6px 10px; color: rgba(255,255,255,.5); }
.nav-submenu .nav-link:hover { color: #fff; background: rgba(255,255,255,.05); }
.sidebar-footer { margin-top: auto; padding: 12px; border-top: 1px solid rgba(255,255,255,.06); }

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

/* ── TOPBAR ── */
.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.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, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

/* ── PAGE ── */
.page { padding: 24px; flex: 1; }
.page-header { margin-bottom: 24px; display:flex; align-items:flex-start; justify-content:space-between; flex-wrap:wrap; gap:12px; }
.page-title  { font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -.4px; }
.page-subtitle { font-size: 13px; color: var(--muted); margin-top: 2px; }

/* ── CHIP ── */
.chip { display:inline-flex; align-items:center; gap:5px; padding:4px 12px; border-radius:50px; font-size:.72rem; font-weight:700; letter-spacing:.6px; text-transform:uppercase; }
.chip-primary { background:var(--primary); color:#fff; }
.chip-green   { background:var(--green);   color:#fff; }
.chip-amber   { background:var(--amber);   color:#fff; }

/* ── WEEKEND BAR ── */
.weekend-bar { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:14px 20px; display:flex; align-items:center; flex-wrap:wrap; gap:12px; margin-bottom:20px; box-shadow:var(--shadow); }
.weekend-bar-title { font-size:.8rem; font-weight:700; color:var(--ink-2); display:flex; align-items:center; gap:7px; }
.toggle-group { display:flex; gap:6px; flex-wrap:wrap; }
.toggle-btn { display:inline-flex; align-items:center; gap:6px; padding:6px 14px; border-radius:50px; font-size:.78rem; font-weight:600; border:1.5px solid var(--border); background:transparent; color:var(--ink-2); cursor:pointer; text-decoration:none; transition:all .2s; }
.toggle-btn.on  { background:var(--green);  color:#fff; border-color:var(--green); }
.toggle-btn.off { background:var(--red-bg); color:var(--red); border-color:#fca5a5; }
.toggle-btn:hover { transform:scale(1.04); }

/* ── ATTENDANCE RULES BAR ── */
.rules-bar { background:var(--primary-bg); border:1px solid #bfdbfe; border-radius:var(--radius); padding:12px 18px; margin-bottom:20px; display:flex; flex-wrap:wrap; gap:16px; align-items:center; font-size:.76rem; color:var(--ink-2); }
.rules-bar b { color:var(--primary); }

/* ── SUCCESS BANNER ── */
.success-banner { background:var(--green-bg); border:1px solid #a7f3d0; color:#065f46; padding:12px 18px; border-radius:var(--radius); margin-bottom:16px; font-size:.85rem; font-weight:600; display:flex; align-items:center; gap:8px; }

/* ── STATS GRID ── */
.stats-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:14px; margin-bottom:24px; }
.scard { background:var(--surface); border-radius:var(--radius); padding:18px 20px; box-shadow:var(--shadow); border:1px solid var(--border); position:relative; overflow:hidden; transition:transform .2s,box-shadow .2s; }
.scard:hover { transform:translateY(-3px); box-shadow:var(--shadow-md); }
.scard::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; border-radius:3px 3px 0 0; }
.scard.blue::before   { background:var(--primary-lt); }
.scard.green::before  { background:var(--green); }
.scard.red::before    { background:var(--red); }
.scard.amber::before  { background:var(--amber); }
.scard.violet::before { background:var(--violet); }
.scard.cyan::before   { background:var(--cyan); }
.scard.pink::before   { background:var(--pink); }
.scard-icon { width:40px; height:40px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:.9rem; margin-bottom:14px; }
.scard-icon.blue   { background:var(--primary-bg); color:var(--primary); }
.scard-icon.green  { background:var(--green-bg);   color:var(--green); }
.scard-icon.red    { background:var(--red-bg);     color:var(--red); }
.scard-icon.amber  { background:var(--amber-bg);   color:var(--amber); }
.scard-icon.violet { background:var(--violet-bg);  color:var(--violet); }
.scard-icon.cyan   { background:var(--cyan-bg);    color:var(--cyan); }
.scard-icon.pink   { background:var(--pink-bg);    color:var(--pink); }
.scard-val   { font-size:1.8rem; font-weight:700; line-height:1; color:var(--ink); }
.scard-label { font-size:.72rem; color:var(--muted); font-weight:600; margin-top:4px; text-transform:uppercase; letter-spacing:.4px; }
.scard-sub   { font-size:.72rem; color:var(--ink-2); margin-top:3px; }

/* ── SECTION CARDS ── */
.section-card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; margin-bottom:24px; }
.section-header { padding:16px 20px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px; }
.section-title  { font-size:15px; font-weight:700; color:var(--ink); display:flex; align-items:center; gap:8px; }
.section-title i { color:var(--muted); }
.section-body   { padding:20px; }

/* ── ATTENDANCE BAR ── */
.att-pct    { font-size:1.5rem; font-weight:700; color:<?php echo $attendance_pct>=80?'var(--green)':($attendance_pct>=50?'var(--amber)':'var(--red)'); ?>; }
.att-bar-wrap { background:var(--bg); border-radius:50px; height:8px; overflow:hidden; margin:12px 0; }
.att-bar-fill { height:100%; border-radius:50px; background:linear-gradient(90deg,var(--primary-lt),var(--green)); width:<?= min(100,$attendance_pct) ?>%; transition:width 1s cubic-bezier(.4,0,.2,1); }
.att-legend { display:flex; flex-wrap:wrap; gap:14px; margin-top:8px; }
.att-leg-item { display:flex; align-items:center; gap:7px; font-size:.78rem; color:var(--ink-2); }
.att-dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }

/* ── HOLIDAY PILLS ── */
.holiday-section { background:var(--amber-bg); border:1px solid #fde68a; border-radius:var(--radius); padding:14px 18px; margin-bottom:20px; }
.holiday-header  { font-size:.8rem; font-weight:700; color:var(--amber); margin-bottom:10px; display:flex; align-items:center; gap:7px; }
.holiday-pills   { display:flex; flex-wrap:wrap; gap:7px; }
.h-pill { background:#fff; border:1px solid #fde68a; border-radius:50px; padding:4px 12px; font-size:.75rem; font-weight:600; color:var(--amber); display:inline-flex; align-items:center; gap:5px; }

/* ── PAYROLL BANNER ── */
.payroll-banner { background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 50%,#1d4ed8 100%); border-radius:var(--radius-lg); padding:20px 24px; display:flex; align-items:center; flex-wrap:wrap; gap:16px; margin-bottom:24px; position:relative; overflow:hidden; }
.payroll-banner::before { content:''; position:absolute; top:-40px; right:-40px; width:160px; height:160px; border-radius:50%; background:rgba(255,255,255,.04); pointer-events:none; }
.pb-icon { width:48px; height:48px; border-radius:12px; background:rgba(255,255,255,.12); display:flex; align-items:center; justify-content:center; font-size:1.2rem; color:#fff; flex-shrink:0; }
.pb-text { flex:1; min-width:160px; }
.pb-title { font-weight:700; font-size:.95rem; color:#fff; }
.pb-sub   { font-size:.78rem; color:rgba(255,255,255,.65); margin-top:3px; }
.pb-stats { display:flex; gap:14px; flex-wrap:wrap; }
.pb-stat  { background:rgba(255,255,255,.1); border-radius:10px; padding:10px 14px; text-align:center; }
.pb-stat-val { font-size:1.2rem; font-weight:700; color:#fff; }
.pb-stat-lbl { font-size:.65rem; color:rgba(255,255,255,.6); margin-top:1px; text-transform:uppercase; letter-spacing:.5px; }
.pb-actions { display:flex; gap:8px; flex-wrap:wrap; }
.pb-btn       { display:inline-flex; align-items:center; gap:7px; padding:9px 16px; border-radius:9px; font-size:.8rem; font-weight:700; font-family:inherit; cursor:pointer; text-decoration:none; transition:all .2s; border:none; }
.pb-btn-white { background:#fff; color:var(--primary); }
.pb-btn-white:hover { background:#f1f5f9; transform:scale(1.03); }
.pb-btn-ghost { background:rgba(255,255,255,.15); color:#fff; border:1.5px solid rgba(255,255,255,.25); }
.pb-btn-ghost:hover { background:rgba(255,255,255,.25); }

/* ── FILTER CARD ── */
.filter-card  { background:var(--surface); border-radius:var(--radius); border:1px solid var(--border); box-shadow:var(--shadow); padding:20px 22px; margin-bottom:24px; }
.filter-title { font-weight:700; font-size:14px; color:var(--ink-2); margin-bottom:16px; display:flex; align-items:center; gap:8px; }
.filter-title i { color:var(--primary); }
.period-tabs { display:flex; gap:5px; flex-wrap:wrap; margin-bottom:16px; }
.p-tab { padding:7px 14px; border-radius:50px; border:1.5px solid var(--border); background:transparent; color:var(--ink-2); font-size:.8rem; font-weight:600; cursor:pointer; transition:all .2s; display:inline-flex; align-items:center; gap:5px; font-family:inherit; }
.p-tab:hover  { border-color:var(--primary-lt); color:var(--primary); }
.p-tab.active { background:var(--primary); color:#fff; border-color:var(--primary); box-shadow:0 3px 10px rgba(29,78,216,.2); }
.fs      { display:none; }
.fs.show { display:block; }
.form-label   { display:block; font-size:.78rem; font-weight:700; color:var(--ink-2); margin-bottom:5px; letter-spacing:.2px; }
.form-control,.form-select-input {
  border:1px solid var(--border); border-radius:8px; font-size:.85rem; color:var(--ink);
  padding:8px 12px; font-family:inherit; transition:border-color .2s,box-shadow .2s;
  background:var(--surface); width:100%; outline:none;
}
.form-control:focus,.form-select-input:focus { border-color:var(--primary-lt); box-shadow:0 0 0 3px rgba(59,130,246,.1); }
.filter-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:14px; margin-top:16px; }
.divider { height:1px; background:var(--border); margin:16px 0; }
.export-row { display:flex; flex-wrap:wrap; gap:9px; align-items:center; }
.export-label { font-size:.78rem; color:var(--muted); font-weight:600; display:flex; align-items:center; gap:5px; }

/* ── BUTTONS ── */
.btn { display:inline-flex; align-items:center; gap:7px; padding:8px 16px; border-radius:9px; font-size:.82rem; font-weight:700; font-family:inherit; border:none; cursor:pointer; transition:all .2s; text-decoration:none; letter-spacing:.1px; }
.btn:hover { transform:translateY(-1px); }
.btn-primary { background:var(--primary); color:#fff; box-shadow:0 3px 10px rgba(29,78,216,.2); }
.btn-primary:hover { background:#1e40af; color:#fff; }
.btn-success { background:var(--green); color:#fff; box-shadow:0 3px 10px rgba(5,150,105,.2); }
.btn-success:hover { background:#047857; color:#fff; }
.btn-danger  { background:var(--red);   color:#fff; box-shadow:0 3px 10px rgba(220,38,38,.2); }
.btn-danger:hover  { background:#b91c1c; color:#fff; }
.btn-amber   { background:var(--amber); color:#fff; }
.btn-amber:hover   { background:#b45309; color:#fff; }
.btn-violet  { background:var(--violet);color:#fff; }
.btn-violet:hover  { background:#6d28d9; color:#fff; }
.btn-pink    { background:var(--pink); color:#fff; }
.btn-pink:hover    { background:#be185d; color:#fff; }
.btn-outline { background:transparent; color:var(--ink-2); border:1.5px solid var(--border); }
.btn-outline:hover { border-color:var(--primary-lt); color:var(--primary); background:var(--primary-bg); }
.btn-sm { padding:6px 12px; font-size:.76rem; border-radius:7px; }
.btn-xs { padding:4px 10px; font-size:.72rem; border-radius:6px; }

/* ── EMP ATTENDANCE TABLE ── */
.emp-att-table-wrap { overflow-x:auto; }
table.att-table { width:100%; border-collapse:collapse; }
table.att-table th { background:#f8fafc; padding:10px 14px; font-size:.7rem; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.5px; border-bottom:1px solid var(--border); text-align:left; white-space:nowrap; }
table.att-table td { padding:11px 14px; font-size:.82rem; color:var(--ink); border-bottom:1px solid #f1f5f9; vertical-align:middle; }
table.att-table tr:last-child td { border-bottom:none; }
table.att-table tr:hover td { background:#fafbfd; }
.att-mini-photo { width:32px; height:32px; border-radius:8px; object-fit:cover; border:1.5px solid var(--border); }
.att-name-cell { display:flex; align-items:center; gap:10px; }
.emp-fn  { font-weight:600; color:var(--ink); font-size:.84rem; }
.emp-div { font-size:.7rem; color:var(--muted); margin-top:1px; }
.days-badge { display:inline-flex; align-items:center; justify-content:center; min-width:34px; padding:3px 9px; border-radius:50px; font-size:.72rem; font-weight:700; }
.days-present { background:var(--green-bg); color:#065f46; }
.days-absent  { background:var(--red-bg);   color:#991b1b; }
.days-late    { background:var(--amber-bg); color:#92400e; }
.days-half    { background:var(--red-bg);   color:#991b1b; }
.days-perm    { background:var(--cyan-bg);  color:#155e75; }
.days-leave   { background:var(--violet-bg);color:#5b21b6; }
.pct-bar { width:70px; height:6px; background:var(--bg); border-radius:50px; overflow:hidden; display:inline-block; vertical-align:middle; margin-left:6px; }
.pct-fill { height:100%; border-radius:50px; transition:width .6s ease; }
.pct-fill.high { background:var(--green); }
.pct-fill.mid  { background:var(--amber); }
.pct-fill.low  { background:var(--red); }
.status-tag { display:inline-flex; align-items:center; gap:4px; padding:3px 10px; border-radius:50px; font-size:.7rem; font-weight:700; }
.tag-ok   { background:var(--green-bg); color:#065f46; }
.tag-warn { background:var(--amber-bg); color:#92400e; }
.tag-bad  { background:var(--red-bg);   color:#991b1b; }
.tag-leave{ background:var(--violet-bg);color:#5b21b6; }

/* ── REPORT CARDS ── */
.report-count-bar { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; margin-bottom:16px; }
.count-text { font-size:.83rem; color:var(--muted); }
.count-text strong { color:var(--ink); }
.reports-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:18px; }

.rcard { background:var(--surface); border-radius:var(--radius-lg); border:1px solid var(--border); box-shadow:var(--shadow); overflow:hidden; transition:transform .25s,box-shadow .25s; }
.rcard:hover { transform:translateY(-4px); box-shadow:var(--shadow-md); }

.rcard-head { padding:16px 18px; background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 55%,#2563eb 100%); display:flex; align-items:center; gap:12px; position:relative; overflow:hidden; }
.rcard-head::after { content:''; position:absolute; top:-25px; right:-25px; width:90px; height:90px; border-radius:50%; background:rgba(255,255,255,.05); pointer-events:none; }
.emp-photo { width:46px; height:46px; border-radius:10px; object-fit:cover; border:2px solid rgba(255,255,255,.3); flex-shrink:0; }
.emp-info  { flex:1; min-width:0; }
.emp-name  { font-weight:700; font-size:.88rem; color:#fff; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.emp-division { font-size:.7rem; color:rgba(255,255,255,.65); margin-top:2px; }
.status-row { display:flex; align-items:center; gap:5px; margin-top:4px; flex-wrap:wrap; }
.status-pip { width:6px; height:6px; border-radius:50%; }
.status-pip.approved { background:#34d399; }
.status-pip.pending  { background:#fbbf24; }
.status-pip.rejected { background:#f87171; }
.status-label { font-size:.7rem; color:rgba(255,255,255,.7); text-transform:capitalize; }
.date-badge { background:rgba(255,255,255,.15); color:#fff; padding:4px 10px; border-radius:50px; font-size:.7rem; font-weight:700; white-space:nowrap; align-self:flex-start; }
.att-badge { padding:2px 9px; border-radius:50px; font-size:.62rem; font-weight:800; text-transform:uppercase; letter-spacing:.4px; }
.att-badge.present    { background:rgba(52,211,153,.2); color:#6ee7b7; }
.att-badge.late       { background:rgba(251,191,36,.2); color:#fcd34d; }
.att-badge.half_day   { background:rgba(248,113,113,.2); color:#fca5a5; }
.att-badge.permission { background:rgba(56,189,248,.2); color:#7dd3fc; }
.att-badge.absent     { background:rgba(248,113,113,.25); color:#fca5a5; }
.att-badge.no_checkout{ background:rgba(220,38,38,.3); color:#fecaca; }
.att-badge.leave      { background:rgba(196,181,253,.25); color:#ddd6fe; }

.att-mini-strip { display:flex; align-items:center; gap:12px; padding:10px 16px; background:#f0f9ff; border-bottom:1px solid #e0f2fe; flex-wrap:wrap; }
.att-mini-item { display:flex; flex-direction:column; align-items:center; min-width:44px; }
.att-mini-val  { font-size:1.05rem; font-weight:700; line-height:1; }
.att-mini-lbl  { font-size:.6rem; font-weight:700; text-transform:uppercase; letter-spacing:.5px; margin-top:2px; color:var(--muted); }
.att-mini-divider { width:1px; height:30px; background:var(--border); }
.att-mini-bar-wrap { flex:1; min-width:60px; }
.att-mini-bar-track { height:5px; background:#e0f2fe; border-radius:50px; overflow:hidden; }
.att-mini-bar-fill  { height:100%; border-radius:50px; transition:width .8s ease; }
.att-mini-pct-lbl   { font-size:.62rem; color:var(--muted); margin-top:2px; text-align:right; }

.rcard-body { padding:0; }
.rrow { display:flex; align-items:flex-start; gap:10px; padding:10px 16px; border-bottom:1px solid #f8fafc; }
.rrow:last-child { border-bottom:none; }
.ri { width:26px; height:26px; border-radius:7px; display:flex; align-items:center; justify-content:center; font-size:.7rem; flex-shrink:0; margin-top:1px; }
.ri.blue   { background:var(--primary-bg); color:var(--primary); }
.ri.green  { background:var(--green-bg);   color:var(--green); }
.ri.red    { background:var(--red-bg);     color:var(--red); }
.ri.amber  { background:var(--amber-bg);   color:var(--amber); }
.ri.violet { background:var(--violet-bg);  color:var(--violet); }
.ri.slate  { background:var(--bg);         color:var(--ink-2); }
.rl { font-size:.65rem; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; margin-bottom:1px; }
.rv { font-size:.83rem; color:var(--ink); line-height:1.5; }
.rv.green { color:#065f46; } .rv.red { color:#991b1b; } .rv.amber { color:#92400e; }

.time-strip { display:flex; background:#fafafa; border-top:1px solid var(--border); padding:10px 16px; gap:10px; flex-wrap:wrap; }
.ti { display:flex; align-items:center; gap:8px; flex:1; min-width:80px; }
.ti-icon  { color:var(--primary-lt); font-size:.75rem; }
.ti-label { font-size:.65rem; color:var(--muted); }
.ti-val   { font-size:.78rem; color:var(--ink-2); font-weight:600; }

.loc-strip { display:flex; flex-wrap:wrap; gap:6px; padding:10px 16px; background:#fafafa; border-top:1px solid var(--border); }
.loc-btn { display:inline-flex; align-items:center; gap:5px; padding:4px 12px; border-radius:50px; font-size:.72rem; font-weight:700; text-decoration:none; transition:all .2s; border:1.5px solid transparent; }
.loc-btn.in  { background:var(--primary-bg); color:var(--primary); border-color:#bfdbfe; }
.loc-btn.in:hover  { background:var(--primary); color:#fff; }
.loc-btn.out { background:var(--violet-bg); color:var(--violet); border-color:#ddd6fe; }
.loc-btn.out:hover { background:var(--violet); color:#fff; }
.selfie-trigger { display:inline-flex; align-items:center; gap:5px; padding:4px 12px; border-radius:50px; font-size:.72rem; font-weight:700; background:var(--green-bg); color:var(--green); border:1.5px solid #a7f3d0; cursor:pointer; transition:all .2s; }
.selfie-trigger:hover { background:var(--green); color:#fff; }

.rcard-foot { padding:8px 16px; background:#fafafa; border-top:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; font-size:.7rem; color:var(--muted); flex-wrap:wrap; gap:6px; }

/* ── MODAL ── */
.modal-overlay { display:none; position:fixed; inset:0; background:rgba(15,23,42,.6); z-index:500; align-items:center; justify-content:center; backdrop-filter:blur(4px); }
.modal-overlay.active { display:flex; }
.modal-box { background:var(--surface); border-radius:var(--radius-lg); overflow:hidden; max-width:600px; width:94%; box-shadow:var(--shadow-md); }
.modal-head { background:linear-gradient(135deg,#0f172a,#1d4ed8); padding:16px 20px; display:flex; align-items:center; justify-content:space-between; }
.modal-head-title { color:#fff; font-weight:700; font-size:.9rem; display:flex; align-items:center; gap:8px; }
.modal-close { background:none; border:none; color:rgba(255,255,255,.7); font-size:1.1rem; cursor:pointer; }
.modal-body { padding:20px; text-align:center; }
.modal-body img { max-width:100%; border-radius:10px; box-shadow:0 8px 32px rgba(0,0,0,.12); }

/* ── CUSTOMISATION MODAL ── */
.cust-row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 0; border-bottom:1px solid #f1f5f9; text-align:left; }
.cust-row:last-child { border-bottom:none; }
.cust-row label { font-size:.82rem; font-weight:600; color:var(--ink-2); }
.cust-row input[type=time] { border:1px solid var(--border); border-radius:8px; padding:6px 10px; font-family:inherit; font-size:.82rem; }

/* ── EMPTY STATE ── */
.empty-state { text-align:center; padding:60px 20px; }
.empty-state .es-icon { font-size:3rem; color:var(--border); margin-bottom:14px; }
.empty-state h5 { font-weight:700; font-size:1rem; color:var(--ink-2); }
.empty-state p  { font-size:.85rem; color:var(--muted); margin-top:5px; }

@media (max-width: 768px) {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .page { padding: 16px; }
  .reports-grid { grid-template-columns: 1fr; }
  .stats-grid { grid-template-columns: repeat(2,1fr); }
  .payroll-banner { padding:16px; }
}
</style>
</head>
<body>
<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</div>
      <div class="brand-sub">Admin Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="manage_users.php"         class="nav-link"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php"     class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="digital.php"              class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"      class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle open" onclick="toggleMenu(this)">
          <i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu open">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link active"><i class="fas fa-chart-line"></i> Daily Report Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="individual_rr.php"     class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php"    class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>  Login Credentials</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dropdown-toggle" onclick="toggleMenu(this)">
          <i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i>
        </button>
        <ul class="nav-submenu">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171;"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </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>CAB</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Daily Reports</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username_session ?: 'A', 0, 1)); ?></div>
      <?php echo h($username_session ?: 'Admin'); ?>
      <span class="chip chip-primary" style="font-size:.65rem"><?= $current_user_role ?></span>
    </div>
  </div>

  <div class="page">

    <div class="page-header">
      <div>
        <div class="page-title">Daily Reports</div>
        <div class="page-subtitle">View, analyse and export employee activity reports</div>
      </div>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <button type="button" class="btn btn-outline btn-sm" onclick="openCustomisation()"><i class="fas fa-sliders-h"></i> Attendance Customisation</button>
        <a href="dashboard_admin.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Dashboard</a>
      </div>
    </div>

    <?php if(isset($_GET['updated'])): ?>
    <div class="success-banner"><i class="fas fa-check-circle"></i> Report updated successfully.</div>
    <?php endif; ?>

    <!-- Weekend Config -->
    <div class="weekend-bar">
      <div class="weekend-bar-title"><i class="fas fa-calendar-week" style="color:var(--primary)"></i> Weekend Configuration</div>
      <div class="toggle-group">
        <a href="?<?= h(http_build_query(array_merge($_GET,['sat_work'=>$sat_work?0:1]))) ?>" class="toggle-btn <?= $sat_work?'on':'off' ?>">
          <i class="fas fa-<?= $sat_work?'check':'times' ?>"></i> Saturday: <?= $sat_work?'Working':'Off' ?>
        </a>
        <a href="?<?= h(http_build_query(array_merge($_GET,['sun_work'=>$sun_work?0:1]))) ?>" class="toggle-btn <?= $sun_work?'on':'off' ?>">
          <i class="fas fa-<?= $sun_work?'check':'times' ?>"></i> Sunday: <?= $sun_work?'Working':'Off' ?>
        </a>
      </div>
      <span style="font-size:.75rem;color:var(--muted);margin-left:auto"><i class="fas fa-info-circle me-1"></i>Affects working days count &amp; attendance %</span>
    </div>

    <!-- Attendance Rules -->
    <div class="rules-bar">
      <span><i class="fas fa-door-open" style="color:var(--primary)"></i> Office hours: <b><?= date('h:i A', strtotime(OFFICE_IN)) ?> – <?= date('h:i A', strtotime(OFFICE_OUT)) ?></b></span>
      <span><i class="fas fa-hourglass-half" style="color:var(--amber)"></i> Late if login after <b><?= date('h:i A', strtotime(LATE_GRACE_UNTIL)) ?></b></span>
      <span><i class="fas fa-business-time" style="color:var(--red)"></i> Half Day if checkout <b><?= date('h:i A', strtotime(HALFDAY_FROM)) ?>–<?= date('h:i A', strtotime(HALFDAY_TO)) ?></b></span>
      <span><i class="fas fa-user-clock" style="color:var(--cyan)"></i> Permission if checkout <b><?= date('h:i A', strtotime(PERMISSION_FROM)) ?>–<?= date('h:i A', strtotime(PERMISSION_TO)) ?></b></span>
      <span><i class="fas fa-check-circle" style="color:var(--green)"></i> Full day if checkout after <b><?= date('h:i A', strtotime(PERMISSION_TO)) ?></b></span>
    </div>

    <!-- Holidays -->
    <?php if(count($holidays_raw)>0): ?>
    <div class="holiday-section">
      <div class="holiday-header"><i class="fas fa-umbrella-beach"></i><?= count($holidays_raw) ?> Holiday<?= count($holidays_raw)!==1?'s':'' ?> in this period</div>
      <div class="holiday-pills">
        <?php foreach($holidays_raw as $hd): ?>
        <span class="h-pill"><i class="fas fa-star" style="font-size:.6rem"></i><?= date('d M',strtotime($hd['holiday_date'])) ?> — <?= h($hd['name']) ?></span>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Payroll Banner -->
    <div class="payroll-banner">
      <div class="pb-icon"><i class="fas fa-coins"></i></div>
      <div class="pb-text">
        <div class="pb-title">Payroll Integration</div>
        <div class="pb-sub">Sync attendance data directly to payroll processing</div>
      </div>
      <div class="pb-stats">
        <div class="pb-stat"><div class="pb-stat-val"><?= $working_days ?></div><div class="pb-stat-lbl">Working Days</div></div>
        <div class="pb-stat"><div class="pb-stat-val"><?= $present_count ?></div><div class="pb-stat-lbl">Present</div></div>
        <div class="pb-stat"><div class="pb-stat-val"><?= $absent_count ?></div><div class="pb-stat-lbl">Absent</div></div>
        <div class="pb-stat"><div class="pb-stat-val"><?= $on_leave_count ?></div><div class="pb-stat-lbl">On Leave</div></div>
        <div class="pb-stat"><div class="pb-stat-val"><?= count($holidays_raw) ?></div><div class="pb-stat-lbl">Holidays</div></div>
      </div>
      <div class="pb-actions">
        <a href="payroll_md_dashboard.php?<?= $payroll_qs ?>" class="pb-btn pb-btn-white"><i class="fas fa-arrow-right"></i> Open Payroll</a>
        <a href="payroll_generate.php?<?= $payroll_qs ?>" class="pb-btn pb-btn-ghost"><i class="fas fa-calculator"></i> Generate Payslips</a>
      </div>
    </div>

    <!-- Stats -->
    <div class="stats-grid">
      <div class="scard blue"><div class="scard-icon blue"><i class="fas fa-file-lines"></i></div><div class="scard-val"><?= $total ?></div><div class="scard-label">Total Reports</div><div class="scard-sub"><?= $selected_period==='day'?date('d M Y',strtotime($selected_date)):ucfirst($selected_period) ?></div></div>
      <div class="scard green"><div class="scard-icon green"><i class="fas fa-user-check"></i></div><div class="scard-val"><?= $present_count ?></div><div class="scard-label">Present</div><div class="scard-sub">Unique employees</div></div>
      <div class="scard red"><div class="scard-icon red"><i class="fas fa-user-xmark"></i></div><div class="scard-val"><?= $absent_count ?></div><div class="scard-label">Absent</div><div class="scard-sub">Out of <?= $total_employees ?> employees</div></div>
      <div class="scard amber"><div class="scard-icon amber"><i class="fas fa-clock"></i></div><div class="scard-val"><?= count($late_reports) ?></div><div class="scard-label">Late Comers</div><div class="scard-sub">Login after <?= date('h:i A', strtotime(LATE_GRACE_UNTIL)) ?></div></div>
      <div class="scard red"><div class="scard-icon red"><i class="fas fa-door-closed"></i></div><div class="scard-val"><?= count($nocheckout_reports) ?></div><div class="scard-label">No Checkout</div><div class="scard-sub">Logged in, never logged out</div></div>
      <div class="scard red"><div class="scard-icon red"><i class="fas fa-business-time"></i></div><div class="scard-val"><?= count($halfday_reports) ?></div><div class="scard-label">Half Day</div><div class="scard-sub">Checkout 1–5 PM</div></div>
      <div class="scard cyan"><div class="scard-icon cyan"><i class="fas fa-user-clock"></i></div><div class="scard-val"><?= count($permission_reports) ?></div><div class="scard-label">Permission</div><div class="scard-sub">Checkout 5–6 PM</div></div>
      <div class="scard violet"><div class="scard-icon violet"><i class="fas fa-umbrella-beach"></i></div><div class="scard-val"><?= count($leave_reports_today) + $on_leave_count ?></div><div class="scard-label">On Leave</div><div class="scard-sub">Approved leave</div></div>
      <div class="scard cyan"><div class="scard-icon cyan"><i class="fas fa-calendar-xmark"></i></div><div class="scard-val"><?= $working_days ?></div><div class="scard-label">Working Days</div><div class="scard-sub"><?= count($holidays_raw) ?> holiday<?= count($holidays_raw)!==1?'s':'' ?> excluded</div></div>
      <div class="scard green"><div class="scard-icon green"><i class="fas fa-circle-check"></i></div><div class="scard-val"><?= count($hits) ?></div><div class="scard-label">With Hits</div><div class="scard-sub">Tasks achieved</div></div>
      <div class="scard red"><div class="scard-icon red"><i class="fas fa-circle-xmark"></i></div><div class="scard-val"><?= count($missed) ?></div><div class="scard-label">With Missed</div><div class="scard-sub">Tasks missed</div></div>
      <div class="scard amber"><div class="scard-icon amber"><i class="fas fa-hourglass-half"></i></div><div class="scard-val"><?= count($pending) ?></div><div class="scard-label">Pending</div><div class="scard-sub">Awaiting approval</div></div>
      <div class="scard violet"><div class="scard-icon violet"><i class="fas fa-percent"></i></div><div class="scard-val"><?= $attendance_pct ?>%</div><div class="scard-label">Attendance</div><div class="scard-sub"><?= $total ?>/<?= $expected_submissions ?> submissions</div></div>
    </div>

    <!-- Attendance Overview -->
    <div class="section-card">
      <div class="section-header">
        <div class="section-title"><i class="fas fa-chart-bar"></i> Attendance Overview</div>
        <div class="att-pct"><?= $attendance_pct ?>%</div>
      </div>
      <div style="padding:16px 20px">
        <div class="att-bar-wrap"><div class="att-bar-fill" id="attBar"></div></div>
        <div class="att-legend">
          <div class="att-leg-item"><div class="att-dot" style="background:var(--green)"></div> Present: <?= $present_count ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--red)"></div> Absent: <?= $absent_count ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--amber)"></div> Late: <?= count($late_reports) ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:#dc2626"></div> No Checkout: <?= count($nocheckout_reports) ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:#dc2626"></div> Half Day: <?= count($halfday_reports) ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--cyan)"></div> Permission: <?= count($permission_reports) ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--violet)"></div> On Leave: <?= $on_leave_count ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--cyan)"></div> Working days: <?= $working_days ?></div>
          <div class="att-leg-item"><div class="att-dot" style="background:var(--amber)"></div> Holidays: <?= count($holidays_raw) ?></div>
          <?php if(!$sat_work): ?><div class="att-leg-item"><div class="att-dot" style="background:var(--border)"></div> Saturday excluded</div><?php endif; ?>
          <?php if(!$sun_work): ?><div class="att-leg-item"><div class="att-dot" style="background:var(--border)"></div> Sunday excluded</div><?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Employee Attendance Breakdown -->
    <?php if(!empty($emp_summary) && $working_days > 0): ?>
    <div class="section-card">
      <div class="section-header">
        <div class="section-title"><i class="fas fa-users"></i> Employee Attendance Breakdown <span class="chip chip-primary" style="font-size:.65rem;margin-left:6px"><?= count($emp_summary) ?> employees</span></div>
        <span style="font-size:.76rem;color:var(--muted)"><i class="fas fa-calendar me-1"></i><?= $working_days ?> working day<?= $working_days!==1?'s':'' ?> in period</span>
      </div>
      <div class="emp-att-table-wrap">
        <table class="att-table">
          <thead>
            <tr>
              <th>Employee</th><th>Emp ID</th><th>Location</th><th>Present</th><th>Absent</th><th>Late</th><th>No Checkout</th><th>Half Day</th><th>Permission</th><th>Leave</th><th>Avg Hrs/Day</th><th>Attendance %</th><th>Status</th><th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php
          $all_emp_q  = "SELECT id, CONCAT(first_name,' ',last_name) AS name, division, photo,
                         COALESCE(NULLIF(work_location,''), NULLIF(location,'')) AS emp_location
                         FROM users 
                         WHERE role IN ('employee','manager') 
                         AND status = 'active'";
          $all_emp_p  = []; $all_emp_t = "";
          if ($selected_div !== 'all') { $all_emp_q .= " AND division=?"; $all_emp_p[] = $selected_div; $all_emp_t .= "s"; }
          if ($selected_loc !== 'all') { $all_emp_q .= " AND COALESCE(NULLIF(work_location,''),NULLIF(location,''))=?"; $all_emp_p[] = $selected_loc; $all_emp_t .= "s"; }
          if ($selected_emp !== 'all') { $all_emp_q .= " AND id=?"; $all_emp_p[] = $selected_emp; $all_emp_t .= "i"; }
          $all_emp_q .= " ORDER BY name ASC";
          $aes = $conn->prepare($all_emp_q);
          if (!empty($all_emp_p)) $aes->bind_param($all_emp_t, ...$all_emp_p);
          $aes->execute();
          $all_emps = $aes->get_result()->fetch_all(MYSQLI_ASSOC);

          foreach ($all_emps as $ae):
            $uid          = $ae['id'];
            $p_days       = isset($emp_summary[$uid]) ? count($emp_summary[$uid]['days']) : 0;
            $emp_reports_list = array_filter($reports, fn($r)=>$r['user_id']==$uid);
            $emp_late    = count(array_filter($emp_reports_list, fn($r)=>$r['_att']['code']==='late'));
            $emp_nocheckout = count(array_filter($emp_reports_list, fn($r)=>$r['_att']['no_checkout']));
            $emp_half    = count(array_filter($emp_reports_list, fn($r)=>$r['_att']['code']==='half_day'));
            $emp_perm    = count(array_filter($emp_reports_list, fn($r)=>$r['_att']['code']==='permission'));
            $emp_leave   = isset($leave_map[$uid]) ? count(array_intersect_key($leave_map[$uid], array_flip(array_filter(array_keys($leave_map[$uid]), fn($d)=>$d>=$range_from && $d<=$range_to)))) : 0;
            $emp_hours_arr = array_filter(array_map(fn($r)=>$r['_att']['hours'], $emp_reports_list), fn($v)=>$v!==null);
            $emp_avg_hours = count($emp_hours_arr) > 0 ? round(array_sum($emp_hours_arr) / count($emp_hours_arr), 1) : 0;
            $a_days       = max(0, $working_days - $p_days - $emp_leave);
            $pct          = $working_days > 0 ? round(($p_days / $working_days) * 100) : 0;
            $bar_class    = $pct >= 80 ? 'high' : ($pct >= 50 ? 'mid' : 'low');
            $status_class = $pct >= 80 ? 'tag-ok' : ($pct >= 50 ? 'tag-warn' : 'tag-bad');
            $status_icon  = $pct >= 80 ? 'fa-circle-check' : ($pct >= 50 ? 'fa-triangle-exclamation' : 'fa-circle-xmark');
            $status_text  = $pct >= 80 ? 'Good' : ($pct >= 50 ? 'Average' : 'Poor');
            $emp_filter_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,'location'=>$selected_loc,'emp_id'=>$uid,'sat_work'=>$sat_work,'sun_work'=>$sun_work]);
          ?>
          <tr>
            <td>
              <div class="att-name-cell">
                <img src="<?= !empty($ae['photo'])?h($ae['photo']):'https://ui-avatars.com/api/?name='.urlencode($ae['name']).'&background=1e3a8a&color=fff&size=64&bold=true&rounded=false' ?>"
                     class="att-mini-photo"
                     onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($ae['name']) ?>&background=1e3a8a&color=fff&size=64&bold=true&rounded=false'">
                <div><div class="emp-fn"><?= h($ae['name']) ?></div><div class="emp-div"><?= h($ae['division'] ?: '—') ?></div></div>
              </div>
            </td>
            <td><span class="chip" style="background:var(--bg);color:var(--ink-2);font-size:.68rem"><?= h($uid) ?></span></td>
            <td><span style="font-size:.78rem;color:var(--ink-2)"><i class="fas fa-map-marker-alt" style="color:var(--muted);margin-right:4px"></i><?= h($ae['emp_location'] ?: '—') ?></span></td>
            <td><span class="days-badge days-present"><?= $p_days ?></span></td>
            <td><span class="days-badge days-absent"><?= $a_days ?></span></td>
            <td><span class="days-badge days-late"><?= $emp_late ?></span></td>
            <td><span class="days-badge days-absent"><?= $emp_nocheckout ?></span></td>
            <td><span class="days-badge days-half"><?= $emp_half ?></span></td>
            <td><span class="days-badge days-perm"><?= $emp_perm ?></span></td>
            <td><span class="days-badge days-leave"><?= $emp_leave ?></span></td>
            <td><strong style="font-size:.83rem"><?= $emp_avg_hours ?>h</strong></td>
            <td>
              <div style="display:flex;align-items:center;gap:6px">
                <strong style="font-size:.83rem;min-width:34px"><?= $pct ?>%</strong>
                <div class="pct-bar"><div class="pct-fill <?= $bar_class ?>" style="width:<?= $pct ?>%"></div></div>
              </div>
            </td>
            <td><span class="status-tag <?= $status_class ?>"><i class="fas <?= $status_icon ?>" style="font-size:.6rem"></i> <?= $status_text ?></span></td>
            <td><a href="?<?= $emp_filter_qs ?>" class="btn btn-outline btn-xs"><i class="fas fa-eye"></i> View</a></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

    <!-- Filter Card -->
    <div class="filter-card">
      <div class="filter-title"><i class="fas fa-sliders"></i> Filter Reports</div>
      <form method="GET" id="filterForm">
        <input type="hidden" name="sat_work" value="<?= $sat_work ?>">
        <input type="hidden" name="sun_work" value="<?= $sun_work ?>">
        <input type="hidden" name="period" id="hiddenPeriod" value="<?= h($selected_period) ?>">

        <div class="period-tabs">
          <button type="button" class="p-tab <?= $selected_period==='day'?'active':'' ?>" data-period="day"><i class="fas fa-calendar-day"></i> Day</button>
          <button type="button" class="p-tab <?= $selected_period==='month'?'active':'' ?>" data-period="month"><i class="fas fa-calendar"></i> Month</button>
          <button type="button" class="p-tab <?= $selected_period==='year'?'active':'' ?>" data-period="year"><i class="fas fa-calendar-days"></i> Year</button>
          <button type="button" class="p-tab <?= $selected_period==='range'?'active':'' ?>" data-period="range"><i class="fas fa-calendar-week"></i> Date Range</button>
        </div>

        <div class="fs <?= $selected_period==='day'?'show':'' ?>" id="fs-day">
          <div><label class="form-label">Date</label><input type="date" name="report_date" class="form-control" style="width:auto" value="<?= h($selected_date) ?>"></div>
        </div>
        <div class="fs <?= $selected_period==='month'?'show':'' ?>" id="fs-month">
          <div><label class="form-label">Month</label><input type="month" name="report_month" class="form-control" style="width:auto" value="<?= h($selected_month) ?>"></div>
        </div>
        <div class="fs <?= $selected_period==='year'?'show':'' ?>" id="fs-year">
          <div><label class="form-label">Year</label>
            <select name="report_year" class="form-select-input" 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 class="fs <?= $selected_period==='range'?'show':'' ?>" id="fs-range">
          <div style="display:flex;gap:14px;flex-wrap:wrap">
            <div><label class="form-label">From</label><input type="date" name="date_from" class="form-control" style="width:auto" value="<?= h($selected_from) ?>"></div>
            <div><label class="form-label">To</label><input type="date" name="date_to" class="form-control" style="width:auto" value="<?= h($selected_to) ?>"></div>
          </div>
        </div>

        <div class="filter-row">
          <div>
            <label class="form-label">Division</label>
            <select name="division" class="form-select-input" id="divSelect">
              <option value="all">All Divisions</option>
              <?php foreach($divisions as $d): ?>
              <option value="<?= h($d['division']) ?>" <?= $selected_div===$d['division']?'selected':'' ?>><?= h($d['division']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="form-label">Location</label>
            <select name="location" class="form-select-input" id="locSelect">
              <option value="all">All Locations</option>
              <?php foreach($locations as $l): if(empty($l['loc'])) continue; ?>
              <option value="<?= h($l['loc']) ?>" <?= $selected_loc===$l['loc']?'selected':'' ?>><?= h($l['loc']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="form-label">Employee</label>
            <select name="emp_id" class="form-select-input">
              <option value="all">All Employees</option>
              <?php foreach($employees as $e): ?>
              <option value="<?= $e['id'] ?>" <?= $selected_emp==$e['id']?'selected':'' ?>><?= h($e['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label class="form-label">Keyword Search</label>
            <div style="position:relative">
              <input type="text" name="search" class="form-control" value="<?= h($search_keyword) ?>" placeholder="Search reports…">
              <i class="fas fa-search" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:.75rem"></i>
            </div>
          </div>
          <div style="display:flex;align-items:flex-end">
            <button type="submit" class="btn btn-primary" style="width:100%"><i class="fas fa-search"></i> Apply Filters</button>
          </div>
        </div>

        <div class="divider"></div>
        <div class="export-row">
          <span class="export-label"><i class="fas fa-download"></i> Export:</span>
          <a href="?export=excel&<?= $exp_qs ?>&sat_work=<?= $sat_work ?>&sun_work=<?= $sun_work ?>" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
          <a href="?export=pdf&<?= $exp_qs ?>&sat_work=<?= $sat_work ?>&sun_work=<?= $sun_work ?>" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
          <a href="?export=matrix&<?= $exp_qs ?>&sat_work=<?= $sat_work ?>&sun_work=<?= $sun_work ?>" class="btn btn-pink btn-sm"><i class="fas fa-table-cells"></i> Attendance Matrix (P/A/L)</a>
          <a href="attendance_summary.php?<?= $payroll_qs ?>" class="btn btn-violet btn-sm"><i class="fas fa-calendar-check"></i> Attendance Report</a>
          <?php if($total>0): ?><span style="margin-left:auto;font-size:.76rem;color:var(--muted)"><?= $total ?> record<?= $total!==1?'s':'' ?> will be exported</span><?php endif; ?>
        </div>
      </form>
    </div>

    <!-- Report Cards -->
    <?php if(empty($reports)): ?>
    <div class="empty-state">
      <div class="es-icon"><i class="fas fa-folder-open"></i></div>
      <h5>No reports found</h5>
      <p>Try adjusting your filters or select a different date/period.</p>
    </div>
    <?php else: ?>

    <div class="report-count-bar">
      <div class="count-text">Showing <strong><?= $total ?></strong> report<?= $total!==1?'s':'' ?></div>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <span class="chip chip-green" style="font-size:.68rem"><?= count($approved) ?> Approved</span>
        <span class="chip chip-amber" style="font-size:.68rem"><?= count($pending) ?> Pending</span>
        <?php if(count($rejected)>0): ?><span class="chip" style="background:var(--red);color:#fff;font-size:.68rem"><?= count($rejected) ?> Rejected</span><?php endif; ?>
        <span class="chip" style="background:var(--amber);color:#fff;font-size:.68rem"><?= count($late_reports) ?> Late</span>
        <span class="chip" style="background:#dc2626;color:#fff;font-size:.68rem"><?= count($nocheckout_reports) ?> No Checkout</span>
        <span class="chip" style="background:var(--red);color:#fff;font-size:.68rem"><?= count($halfday_reports) ?> Half Day</span>
        <span class="chip" style="background:var(--cyan);color:#fff;font-size:.68rem"><?= count($permission_reports) ?> Permission</span>
      </div>
    </div>

    <div class="reports-grid">
    <?php
    $emp_present_days_card = [];
    foreach($reports as $r) {
      $uid = $r['user_id'];
      if (!isset($emp_present_days_card[$uid])) $emp_present_days_card[$uid] = [];
      if (!in_array($r['report_date'], $emp_present_days_card[$uid])) $emp_present_days_card[$uid][] = $r['report_date'];
    }

    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   = !empty($r['photo']) ? $r['photo'] : '';
      $selfie  = !empty($r['photo_path']) ? $r['photo_path'] : '';
      $status  = strtolower($r['approval_status'] ?? 'pending');
      $is_holiday = in_array($r['report_date'], $holiday_dates);
      $dow = date('w', strtotime($r['report_date']));
      $is_weekend = ($dow==0&&!$sun_work)||($dow==6&&!$sat_work);
      $card_uid    = $r['user_id'];
      $card_p_days = isset($emp_present_days_card[$card_uid]) ? count($emp_present_days_card[$card_uid]) : 0;
      $card_a_days = max(0, $working_days - $card_p_days);
      $card_pct    = $working_days > 0 ? round(($card_p_days / $working_days) * 100) : 0;
      $card_bar_col = $card_pct >= 80 ? 'var(--green)' : ($card_pct >= 50 ? 'var(--amber)' : 'var(--red)');
      $att = $r['_att'];
    ?>
    <div class="rcard">
      <div class="rcard-head">
        <img src="<?= $photo ? h($photo) : 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MiA1MiI+PHJlY3Qgd2lkdGg9IjUyIiBoZWlnaHQ9IjUyIiBmaWxsPSIjMWUzYThhIi8+PC9zdmc+' ?>"
             class="emp-photo"
             onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($r['emp_name']) ?>&background=1e3a8a&color=fff&size=50&bold=true&rounded=false'">
        <div class="emp-info">
          <div class="emp-name"><?= h($r['emp_name']) ?></div>
          <div class="emp-division">
            ID: <?= h($r['emp_id'] ?? $r['user_id']) ?>
            · <?= h($r['division'] ?: '—') ?>
            <?php if(!empty($r['emp_location'])): ?> · <i class="fas fa-map-marker-alt"></i> <?= h($r['emp_location']) ?><?php endif; ?>
            <?php if($r['location_type']): ?> · <?= h($r['location_type']) ?><?php endif; ?>
            <?php if($is_holiday): ?> · <span style="color:#fbbf24">🏖 Holiday</span><?php endif; ?>
            <?php if($is_weekend): ?> · <span style="color:rgba(255,255,255,.5)">Weekend</span><?php endif; ?>
          </div>
          <div class="status-row">
            <div class="status-pip <?= $status==='approved'?'approved':($status==='rejected'?'rejected':'pending') ?>"></div>
            <span class="status-label"><?= h($status) ?></span>
            <span class="att-badge <?= $att['code'] ?>"><i class="fas fa-circle" style="font-size:.5rem;margin-right:3px"></i><?= h($att['label']) ?></span>
            <?php if(!empty($r['_on_leave'])): ?><span class="att-badge leave"><i class="fas fa-umbrella-beach" style="font-size:.6rem;margin-right:3px"></i><?= h($r['_on_leave']) ?></span><?php endif; ?>
          </div>
        </div>
        <?php if($r['report_date']): ?><div class="date-badge"><?= date('d M Y',strtotime($r['report_date'])) ?></div><?php endif; ?>
      </div>

      <?php if($working_days > 1): ?>
      <div class="att-mini-strip">
        <div class="att-mini-item"><div class="att-mini-val" style="color:var(--green)"><?= $card_p_days ?></div><div class="att-mini-lbl">Present</div></div>
        <div class="att-mini-divider"></div>
        <div class="att-mini-item"><div class="att-mini-val" style="color:var(--red)"><?= $card_a_days ?></div><div class="att-mini-lbl">Absent</div></div>
        <div class="att-mini-divider"></div>
        <div class="att-mini-item"><div class="att-mini-val" style="color:var(--cyan)"><?= $working_days ?></div><div class="att-mini-lbl">Working</div></div>
        <div class="att-mini-divider"></div>
        <div class="att-mini-bar-wrap">
          <div class="att-mini-bar-track"><div class="att-mini-bar-fill" style="width:<?= $card_pct ?>%;background:<?= $card_bar_col ?>"></div></div>
          <div class="att-mini-pct-lbl"><?= $card_pct ?>% attendance</div>
        </div>
      </div>
      <?php endif; ?>

      <div class="rcard-body">
        <?php if($r['client_name']): ?><div class="rrow"><div class="ri blue"><i class="fas fa-building"></i></div><div><div class="rl">Client</div><div class="rv"><?= nl2br(h($r['client_name'])) ?></div></div></div><?php endif; ?>
        <?php if($r['Morning']): ?><div class="rrow"><div class="ri blue"><i class="fas fa-sun"></i></div><div><div class="rl">Morning Plan</div><div class="rv"><?= nl2br(h($r['Morning'])) ?></div></div></div><?php endif; ?>
        <?php if($r['Hits']): ?><div class="rrow"><div class="ri green"><i class="fas fa-check-circle"></i></div><div><div class="rl">Hits</div><div class="rv green"><?= nl2br(h($r['Hits'])) ?></div></div></div><?php endif; ?>
        <?php if($r['Missed']): ?><div class="rrow"><div class="ri red"><i class="fas fa-times-circle"></i></div><div><div class="rl">Missed</div><div class="rv red"><?= nl2br(h($r['Missed'])) ?></div></div></div><?php endif; ?>
        <?php if($r['carry forward']): ?><div class="rrow"><div class="ri amber"><i class="fas fa-forward"></i></div><div><div class="rl">Carry Forward</div><div class="rv amber"><?= nl2br(h($r['carry forward'])) ?></div></div></div><?php endif; ?>
        <?php if($r['daily_summary']): ?><div class="rrow"><div class="ri violet"><i class="fas fa-clipboard-list"></i></div><div><div class="rl">Daily Summary</div><div class="rv"><?= nl2br(h($r['daily_summary'])) ?></div></div></div><?php endif; ?>
        <?php if($r['manager_remark']): ?><div class="rrow"><div class="ri slate"><i class="fas fa-comment-dots"></i></div><div><div class="rl">Manager Remark</div><div class="rv"><?= nl2br(h($r['manager_remark'])) ?></div></div></div><?php endif; ?>

        <div class="time-strip">
          <div class="ti"><i class="fas fa-right-to-bracket ti-icon"></i><div><div class="ti-label">Login</div><div class="ti-val"><?= h($r['login_time'] ?? '—') ?></div></div></div>
          <div class="ti"><i class="fas fa-right-from-bracket ti-icon"></i><div><div class="ti-label">Logout</div><div class="ti-val"><?= h($r['logout_time'] ?? '—') ?></div></div></div>
          <div class="ti" style="justify-content:flex-end;text-align:right"><div><div class="ti-label">Hours Worked</div><div class="ti-val"><?= $att['hours']!==null ? $att['hours'].' hrs' : '—' ?></div></div><i class="fas fa-hourglass-half ti-icon"></i></div>
        </div>

        <?php if($login_map || $logout_map || $selfie): ?>
        <div class="loc-strip">
          <?php if($login_map): ?><a href="<?= $login_map ?>" target="_blank" class="loc-btn in"><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-trigger" onclick="openSelfie('<?= h($selfie) ?>','<?= h($r['emp_name']) ?>')"><i class="fas fa-camera"></i> Selfie</button><?php endif; ?>
        </div>
        <?php endif; ?>
      </div>

      <div class="rcard-foot">
        <span><i class="fas fa-clock" style="margin-right:4px"></i><?= date('d M Y, h:i A',strtotime($r['created_at'])) ?></span>
        <div style="display:flex;align-items:center;gap:6px">
          <?php if($is_admin && isset($r['id'])): ?>
          <button type="button" class="btn btn-outline btn-xs" onclick='openUpdateModal(<?= (int)$r['id'] ?>, <?= json_encode($r['login_time'] ?? '') ?>, <?= json_encode($r['logout_time'] ?? '') ?>, <?= json_encode($r['manager_remark'] ?? '') ?>, <?= json_encode($status) ?>)'>
            <i class="fas fa-pen"></i> Update
          </button>
          <?php endif; ?>
          <span class="chip <?= $status==='approved'?'chip-green':($status==='rejected'?'':'chip-amber') ?>" style="<?= $status==='rejected'?'background:var(--red);color:#fff':'' ?>;font-size:.64rem"><?= ucfirst($status) ?></span>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>

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

<!-- SELFIE MODAL -->
<div class="modal-overlay" id="selfieModal">
  <div class="modal-box">
    <div class="modal-head">
      <div class="modal-head-title"><i class="fas fa-camera"></i> <span id="modalEmpName"></span></div>
      <button class="modal-close" onclick="closeSelfie()"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
      <img id="modalSelfieImg" src="" alt="Selfie">
    </div>
  </div>
</div>

<!-- ATTENDANCE CUSTOMISATION MODAL -->
<div class="modal-overlay" id="custModal">
  <div class="modal-box" style="max-width:440px">
    <div class="modal-head">
      <div class="modal-head-title"><i class="fas fa-sliders-h"></i> Attendance Customisation</div>
      <button class="modal-close" onclick="closeCustomisation()"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body" style="text-align:left">
      <p style="font-size:.78rem;color:var(--muted);margin-bottom:10px">These are the current office-hour rules used to compute Late / Half Day / Permission status. To change them, update the <code>OFFICE_IN</code>, <code>LATE_GRACE_UNTIL</code>, <code>HALFDAY_FROM/TO</code> and <code>PERMISSION_FROM/TO</code> constants near the top of <code>daily_reports_dashboard.php</code>.</p>
      <div class="cust-row"><label>Office Start</label><input type="time" value="<?= date('H:i', strtotime(OFFICE_IN)) ?>" disabled></div>
      <div class="cust-row"><label>Late After</label><input type="time" value="<?= date('H:i', strtotime(LATE_GRACE_UNTIL)) ?>" disabled></div>
      <div class="cust-row"><label>Half Day Window</label><span style="font-size:.8rem"><?= date('h:i A', strtotime(HALFDAY_FROM)) ?> – <?= date('h:i A', strtotime(HALFDAY_TO)) ?></span></div>
      <div class="cust-row"><label>Permission Window</label><span style="font-size:.8rem"><?= date('h:i A', strtotime(PERMISSION_FROM)) ?> – <?= date('h:i A', strtotime(PERMISSION_TO)) ?></span></div>
      <div class="cust-row"><label>Office End</label><input type="time" value="<?= date('H:i', strtotime(OFFICE_OUT)) ?>" disabled></div>
    </div>
  </div>
</div>

<!-- UPDATE REPORT MODAL -->
<div class="modal-overlay" id="updateModal">
  <div class="modal-box" style="max-width:460px">
    <div class="modal-head">
      <div class="modal-head-title"><i class="fas fa-pen"></i> Update Report</div>
      <button class="modal-close" onclick="closeUpdateModal()"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body" style="text-align:left">
      <form method="POST" action="daily_reports_dashboard.php?<?= h(http_build_query($_GET)) ?>">
        <input type="hidden" name="update_report" value="1">
        <input type="hidden" name="report_id" id="upd_report_id" value="">
        <div style="margin-bottom:12px">
          <label class="form-label">Login Time</label>
          <input type="text" name="login_time" id="upd_login_time" class="form-control" placeholder="e.g. 2026-08-11 09:25:00">
        </div>
        <div style="margin-bottom:12px">
          <label class="form-label">Logout Time</label>
          <input type="text" name="logout_time" id="upd_logout_time" class="form-control" placeholder="e.g. 2026-08-11 18:10:00">
        </div>
        <div style="margin-bottom:12px">
          <label class="form-label">Manager Remark</label>
          <textarea name="manager_remark" id="upd_manager_remark" class="form-control" rows="3"></textarea>
        </div>
        <div style="margin-bottom:16px">
          <label class="form-label">Approval Status</label>
          <select name="approval_status" id="upd_approval_status" class="form-select-input">
            <option value="pending">Pending</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
          </select>
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%"><i class="fas fa-save"></i> Save Changes</button>
      </form>
    </div>
  </div>
</div>

<script>
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.nextElementSibling.classList.toggle('open');
  btn.classList.toggle('open');
}

// Period tabs
const tabs = document.querySelectorAll('.p-tab');
const hp   = document.getElementById('hiddenPeriod');
const secs = { day:'fs-day', month:'fs-month', year:'fs-year', range:'fs-range' };
function showPeriod(p) {
  tabs.forEach(t => t.classList.toggle('active', t.dataset.period === p));
  hp.value = p;
  Object.entries(secs).forEach(([k,id]) => document.getElementById(id).classList.toggle('show', k === p));
}
tabs.forEach(t => t.addEventListener('click', () => showPeriod(t.dataset.period)));

// Division change
document.getElementById('divSelect').addEventListener('change', function() {
  const url = new URL(window.location);
  url.searchParams.set('division', this.value);
  url.searchParams.set('period', hp.value);
  url.searchParams.set('sat_work', '<?= $sat_work ?>');
  url.searchParams.set('sun_work', '<?= $sun_work ?>');
  url.searchParams.delete('emp_id');
  window.location = url.toString();
});

// Location change
document.getElementById('locSelect').addEventListener('change', function() {
  const url = new URL(window.location);
  url.searchParams.set('location', this.value);
  url.searchParams.set('period', hp.value);
  url.searchParams.set('sat_work', '<?= $sat_work ?>');
  url.searchParams.set('sun_work', '<?= $sun_work ?>');
  url.searchParams.delete('emp_id');
  window.location = url.toString();
});

// Selfie modal
function openSelfie(src, name) {
  document.getElementById('modalSelfieImg').src = src;
  document.getElementById('modalEmpName').textContent = name + ' — Selfie';
  document.getElementById('selfieModal').classList.add('active');
}
function closeSelfie() {
  document.getElementById('selfieModal').classList.remove('active');
}
document.getElementById('selfieModal').addEventListener('click', function(e) {
  if (e.target === this) closeSelfie();
});

// Customisation modal
function openCustomisation() { document.getElementById('custModal').classList.add('active'); }
function closeCustomisation() { document.getElementById('custModal').classList.remove('active'); }
document.getElementById('custModal').addEventListener('click', function(e) {
  if (e.target === this) closeCustomisation();
});

// Update report modal
function openUpdateModal(id, login, logout, remark, status) {
  document.getElementById('upd_report_id').value = id;
  document.getElementById('upd_login_time').value = login || '';
  document.getElementById('upd_logout_time').value = logout || '';
  document.getElementById('upd_manager_remark').value = remark || '';
  document.getElementById('upd_approval_status').value = status || 'pending';
  document.getElementById('updateModal').classList.add('active');
}
function closeUpdateModal() { document.getElementById('updateModal').classList.remove('active'); }
document.getElementById('updateModal').addEventListener('click', function(e) {
  if (e.target === this) closeUpdateModal();
});

// Animate bars on load
document.addEventListener('DOMContentLoaded', () => {
  const bar = document.getElementById('attBar');
  if (bar) { bar.style.width = '0%'; setTimeout(() => bar.style.width = '<?= min(100,$attendance_pct) ?>%', 200); }
  document.querySelectorAll('.pct-fill').forEach(el => {
    const w = el.style.width; el.style.width = '0%'; setTimeout(() => el.style.width = w, 300);
  });
  document.querySelectorAll('.att-mini-bar-fill').forEach(el => {
    const w = el.style.width; el.style.width = '0%'; setTimeout(() => el.style.width = w, 400);
  });
});
</script>
</body>
</html>
<?php $conn->close(); ?>