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

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

$username = $_SESSION['username'] ?? 'MD';

$users_stmt = $conn->prepare("SELECT id, username, first_name, last_name FROM users WHERE role = 'employee' ORDER BY first_name, last_name");
$users_stmt->execute();
$all_employees = $users_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$selected_date    = $_GET['att_date'] ?? date('Y-m-d');
$selected_user_id = $_GET['user_id'] ?? 'all';

$att_sql = "SELECT ma.*, u.username, CONCAT(u.first_name,' ',u.last_name) AS full_name, u.photo
            FROM mobileattendance ma JOIN users u ON ma.user_id = u.id
            WHERE ma.attendance_date = ?";
$params = [$selected_date]; $types = "s";
if ($selected_user_id !== 'all') { $att_sql .= " AND ma.user_id = ?"; $params[] = $selected_user_id; $types .= "i"; }
$att_sql .= " ORDER BY ma.login_time DESC";
$stmt = $conn->prepare($att_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$date_attendance = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$today = date('Y-m-d');
$today_stmt = $conn->prepare("
    SELECT ma.*, CONCAT(u.first_name,' ',u.last_name) AS full_name, u.photo
    FROM mobileattendance ma JOIN users u ON ma.user_id = u.id
    WHERE ma.attendance_date = ? ORDER BY ma.login_time DESC");
$today_stmt->bind_param("s", $today);
$today_stmt->execute();
$today_attendance = $today_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>
<!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 · Attendance</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=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;
  --l3:#059669;--radius:12px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.06);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'Sora',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}
.sidebar{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{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;transition:background .15s,color .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}.nav-link.active{background:rgba(59,130,246,.2);color:#60a5fa}
.nav-link i{width:16px;text-align:center;font-size:13px}.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.12);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px;border-top:1px solid rgba(255,255,255,.06)}
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s cubic-bezier(.4,0,.2,1)}
.content.expanded{margin-left:0}
.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}
.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{padding:24px;flex:1}
.page-title{font-size:22px;font-weight:700;color:var(--ink);letter-spacing:-.4px;margin-bottom:4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-bottom:20px}

/* FILTER BAR */
.filter-bar{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;padding:14px 16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:20px;box-shadow:var(--shadow)}
.filter-group{display:flex;flex-direction:column;gap:4px}.filter-group.grow{flex:1;min-width:200px}
.filter-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}
.filter-select,.filter-input{height:36px;border:1px solid var(--border);border-radius:8px;padding:0 10px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s;min-width:140px}
.filter-select:focus,.filter-input:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12);background:var(--surface)}
.filter-btn{height:36px;padding:0 16px;border-radius:8px;border:none;cursor:pointer;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;display:flex;align-items:center;gap:6px;transition:background .15s}
.btn-primary-sm{background:#0f172a;color:#fff}.btn-primary-sm:hover{background:#1e293b}

/* SECTION HEADER */
.section-head{font-size:14px;font-weight:700;color:var(--ink);margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:8px}
.section-badge{display:inline-flex;align-items:center;justify-content:center;padding:2px 9px;border-radius:20px;font-size:11px;font-weight:700;background:#dbeafe;color:#1d4ed8;font-family:'JetBrains Mono',monospace}

/* TABLE */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;margin-bottom:20px}
.tbl-wrap{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:13px}
thead th{background:var(--ink);color:rgba(255,255,255,.85);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.7px;padding:10px 14px;text-align:left;white-space:nowrap}
tbody td{padding:10px 14px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
tbody tr:last-child td{border-bottom:none}
tbody tr:hover td{background:#f8fafc}
.emp-thumb{width:36px;height:36px;border-radius:50%;object-fit:cover;border:2px solid var(--border)}
.map-link{display:inline-flex;align-items:center;gap:5px;color:#2563eb;font-size:12px;font-weight:600;text-decoration:none}
.map-link:hover{color:#1d4ed8;text-decoration:underline}
.hours-chip{display:inline-flex;align-items:center;gap:5px;background:#d1fae5;color:#065f46;border-radius:20px;padding:3px 10px;font-size:11px;font-weight:700;font-family:'JetBrains Mono',monospace}
.active-chip{background:#fef3c7;color:#92400e}

/* TODAY GRID */
.today-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;margin-bottom:20px}
.emp-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;transition:box-shadow .2s,transform .2s}
.emp-card:hover{box-shadow:var(--shadow-md);transform:translateY(-2px)}
.ec-header{background:var(--ink);padding:14px;display:flex;align-items:center;gap:12px}
.ec-avatar{width:52px;height:52px;border-radius:50%;object-fit:cover;border:3px solid rgba(255,255,255,.2);flex-shrink:0}
.ec-name{font-size:13px;font-weight:700;color:#fff}
.ec-time{font-size:11px;color:rgba(255,255,255,.5);margin-top:2px}
.ec-body{padding:14px}
.ec-meta{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}

.empty-state{text-align:center;padding:48px;color:var(--muted)}
.empty-state i{font-size:36px;margin-bottom:12px;opacity:.4;display:block}
.empty-state p{font-size:14px}

@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{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">MD Portal</div></div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_md.php"               class="nav-link"><i class="fas fa-sitemap"></i> Organisation</a></li>
      <li class="nav-item"><a href="payroll_md_dashboard.php"       class="nav-link"><i class="fas fa-money-bill"></i> Payroll</a></li>
      <li class="nav-item"><a href="daily_reports_dashboard_md.php" class="nav-link"><i class="fas fa-chart-line"></i> Reports</a></li>
      <li class="nav-item"><a href="md_leave_approval.php"          class="nav-link"><i class="fas fa-umbrella-beach"></i> Leave Approval</a></li>
      <li class="nav-item"><a href="mdmobile.php"                   class="nav-link active"><i class="fas fa-mobile-alt"></i> Attendance</a></li>
      <li class="nav-item"><a href="tasks_md.php"                   class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link danger"><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>Attendance</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">Daily Attendance</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username,0,1)) ?></div>
      <?= htmlspecialchars($username) ?>
    </div>
  </div>

  <div class="page">
    <div class="page-title">Attendance Dashboard</div>
    <div class="page-subtitle">Track daily employee check-ins and check-outs</div>

    <!-- Filter -->
    <form method="get">
      <div class="filter-bar">
        <div class="filter-group">
          <span class="filter-label">Select Date</span>
          <input type="date" name="att_date" value="<?= htmlspecialchars($selected_date) ?>" class="filter-input" style="min-width:170px">
        </div>
        <div class="filter-group grow">
          <span class="filter-label">Employee</span>
          <select name="user_id" class="filter-select">
            <option value="all">All Employees</option>
            <?php foreach ($all_employees as $emp): ?>
            <option value="<?= $emp['id'] ?>" <?= $selected_user_id == $emp['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($emp['first_name'].' '.$emp['last_name']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="display:flex;gap:6px;align-items:flex-end">
          <button type="submit" class="filter-btn btn-primary-sm"><i class="fas fa-search"></i> View</button>
        </div>
      </div>
    </form>

    <!-- Date-wise results -->
    <?php if (!empty($date_attendance)): ?>
    <div class="section-head">
      <i class="fas fa-calendar-check" style="color:#059669"></i>
      Attendance on <?= date('d M Y', strtotime($selected_date)) ?>
      <span class="section-badge"><?= count($date_attendance) ?> record<?= count($date_attendance)!=1?'s':'' ?></span>
    </div>
    <div class="card">
      <div class="tbl-wrap">
        <table>
          <thead>
            <tr>
              <th>Photo</th><th>Name</th>
              <th>Login</th><th>Login Location</th>
              <th>Logout</th><th>Logout Location</th>
              <th>Hours</th><th>Selfie</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($date_attendance as $row):
              $login_map  = $row['latitude']&&$row['longitude'] ? "https://maps.google.com/?q={$row['latitude']},{$row['longitude']}" : '';
              $logout_map = $row['logout_latitude']&&$row['logout_longitude'] ? "https://maps.google.com/?q={$row['logout_latitude']},{$row['logout_longitude']}" : '';
              $hours = ($row['logout_time']&&$row['login_time'])
                ? round((strtotime($row['logout_time'])-strtotime($row['login_time']))/3600,2).' hrs'
                : ($row['logout_time']?'—':'In Progress');
            ?>
            <tr>
              <td><img src="<?= $row['photo']?:'uploads/default-profile.png' ?>" class="emp-thumb" onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($row['full_name']) ?>&background=e2e8f0&color=64748b&size=36'"></td>
              <td style="font-weight:600"><?= htmlspecialchars($row['full_name']) ?></td>
              <td style="font-family:'JetBrains Mono',monospace"><?= $row['login_time'] ? date('h:i A', strtotime($row['login_time'])) : '—' ?></td>
              <td><?= $login_map ? "<a href='$login_map' target='_blank' class='map-link'><i class='fas fa-map-marker-alt'></i> View</a>" : '—' ?></td>
              <td style="font-family:'JetBrains Mono',monospace"><?= $row['logout_time'] ? date('h:i A',strtotime($row['logout_time'])) : '<span style="color:#f59e0b;font-weight:600">Active</span>' ?></td>
              <td><?= $logout_map ? "<a href='$logout_map' target='_blank' class='map-link'><i class='fas fa-map-marker-alt'></i> View</a>" : '—' ?></td>
              <td>
                <?php if ($row['logout_time']&&$row['login_time']): ?>
                  <span class="hours-chip"><i class="fas fa-clock"></i> <?= $hours ?></span>
                <?php elseif (!$row['logout_time']): ?>
                  <span class="hours-chip active-chip"><i class="fas fa-circle" style="font-size:6px"></i> In Progress</span>
                <?php else: ?>—<?php endif; ?>
              </td>
              <td><?= $row['photo_path']&&file_exists($row['photo_path']) ? "<a href='{$row['photo_path']}' target='_blank' class='map-link'><i class='fas fa-camera'></i> View</a>" : '—' ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php elseif ($selected_date !== $today): ?>
    <div class="card">
      <div class="empty-state">
        <i class="fas fa-calendar-times"></i>
        <p style="font-weight:600;margin-bottom:4px">No attendance found</p>
        <p style="font-size:12px">No records for <?= date('d M Y', strtotime($selected_date)) ?></p>
      </div>
    </div>
    <?php endif; ?>

    <!-- Today's Summary -->
    <div class="section-head">
      <i class="fas fa-users" style="color:#3b82f6"></i>
      Today's Attendance — <?= date('d M Y') ?>
      <span class="section-badge"><?= count($today_attendance) ?> present</span>
    </div>

    <?php if (empty($today_attendance)): ?>
    <div class="card">
      <div class="empty-state">
        <i class="fas fa-user-slash"></i>
        <p style="font-weight:600;margin-bottom:4px">No attendance yet</p>
        <p style="font-size:12px">No one has marked attendance today.</p>
      </div>
    </div>
    <?php else: ?>
    <div class="today-grid">
      <?php foreach ($today_attendance as $emp):
        $map_url = $emp['latitude']&&$emp['longitude'] ? "https://maps.google.com/?q={$emp['latitude']},{$emp['longitude']}" : '';
        $hrs = ($emp['logout_time']&&$emp['login_time'])
          ? round((strtotime($emp['logout_time'])-strtotime($emp['login_time']))/3600,2).' hrs'
          : (!$emp['logout_time'] ? 'In Progress' : '—');
      ?>
      <div class="emp-card">
        <div class="ec-header">
          <img src="<?= $emp['photo']?:'uploads/default-profile.png' ?>" class="ec-avatar"
               onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($emp['full_name']) ?>&background=334155&color=ffffff&size=52'">
          <div>
            <div class="ec-name"><?= htmlspecialchars($emp['full_name']) ?></div>
            <div class="ec-time">Login: <?= date('h:i A', strtotime($emp['login_time'])) ?></div>
          </div>
        </div>
        <div class="ec-body">
          <div class="ec-meta">
            <div style="font-size:12px;color:var(--muted)">
              Logout: <?= $emp['logout_time'] ? '<strong style="color:var(--ink)">'.date('h:i A',strtotime($emp['logout_time'])).'</strong>' : '<span style="color:#f59e0b;font-weight:600">Still Working</span>' ?>
            </div>
            <?php if ($emp['logout_time']&&$emp['login_time']): ?>
              <span class="hours-chip"><i class="fas fa-clock"></i> <?= $hrs ?></span>
            <?php else: ?>
              <span class="hours-chip active-chip"><i class="fas fa-circle" style="font-size:6px"></i> Active</span>
            <?php endif; ?>
          </div>
          <?php if ($map_url): ?>
          <a href="<?= $map_url ?>" target="_blank" class="map-link" style="font-size:12px"><i class="fas fa-map-marker-alt"></i> View Location</a>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

  </div>
</div>
</div>

<script>
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
</script>
</body>
</html>
<?php $conn->close(); ?>