<?php
ini_set('display_errors',1); error_reporting(E_ALL & ~E_DEPRECATED);
session_start();
require 'config.php';

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

$md_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'MD';
$status_filter = $_GET['status'] ?? 'Pending';

$countStmt = $conn->prepare("
  SELECT
    SUM(CASE WHEN status='Pending'  THEN 1 ELSE 0 END) AS pending_count,
    SUM(CASE WHEN status='Approved' THEN 1 ELSE 0 END) AS approved_count,
    SUM(CASE WHEN status='Rejected' THEN 1 ELSE 0 END) AS rejected_count
  FROM leave_requests WHERE md_id = ?");
$countStmt->bind_param("s", $md_id);
$countStmt->execute();
$countData = $countStmt->get_result()->fetch_assoc();

$stmt = $conn->prepare("
  SELECT lr.id, lr.leave_type, lr.start_date, lr.end_date,
         lr.permission_date, lr.permission_time_from, lr.permission_time_to, lr.permission_hours,
         lr.reason, lr.work_description, lr.status, lr.md_comment, lr.applied_on,
         u.username, u.role
  FROM leave_requests lr JOIN users u ON lr.employee_id = u.id
  WHERE lr.md_id = ? AND lr.status = ?
  ORDER BY lr.applied_on DESC");
$stmt->bind_param("ss", $md_id, $status_filter);
$stmt->execute();
$result = $stmt->get_result();
?>
<!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 · Leave Approval</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;--l5:#dc2626;--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)}

/* STAT GRID */
.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:20px 0}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);position:relative;overflow:hidden}
.stat-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:3px 3px 0 0}
.stat-pend::before{background:#f59e0b}.stat-appr::before{background:var(--l3)}.stat-rej::before{background:var(--l5)}
.stat-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px;margin-bottom:8px}
.stat-pend .stat-icon{background:#fef3c7;color:#d97706}.stat-appr .stat-icon{background:#d1fae5;color:#059669}.stat-rej .stat-icon{background:#fee2e2;color:#dc2626}
.stat-num{font-size:28px;font-weight:700;font-family:'JetBrains Mono',monospace;color:var(--ink);line-height:1;margin-bottom:3px}
.stat-lbl{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}

/* TABS */
.tabs-wrap{display:flex;gap:4px;background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:4px;width:fit-content;margin-bottom:16px;box-shadow:var(--shadow)}
.tab-btn{padding:7px 20px;border:none;background:none;border-radius:7px;font-size:13px;font-weight:600;font-family:'Sora',sans-serif;color:var(--muted);cursor:pointer;display:flex;align-items:center;gap:6px;transition:background .15s,color .15s;text-decoration:none}
.tab-btn:hover{color:var(--ink);background:var(--bg)}.tab-btn.active{background:var(--ink);color:#fff}

/* CARD / TABLE */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden}
.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:top}
tbody tr:last-child td{border-bottom:none}
tbody tr:hover td{background:#f8fafc}
.empty-cell{text-align:center;padding:48px;color:var(--muted)}
.empty-cell i{font-size:36px;display:block;margin-bottom:12px;opacity:.4}

/* ACTION BTNS */
.btn-approve{background:#059669;color:#fff;border:none;padding:6px 14px;border-radius:7px;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;cursor:pointer;width:100%;margin-bottom:4px;transition:background .15s}
.btn-approve:hover{background:#047857}
.btn-reject{background:#dc2626;color:#fff;border:none;padding:6px 14px;border-radius:7px;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;cursor:pointer;width:100%;transition:background .15s}
.btn-reject:hover{background:#b91c1c}
textarea.comment-box{width:100%;border:1px solid var(--border);border-radius:7px;padding:7px 10px;font-size:12px;font-family:'Sora',sans-serif;resize:vertical;min-height:60px;margin-bottom:6px;background:var(--bg);outline:none;transition:border-color .15s}
textarea.comment-box:focus{border-color:#3b82f6;background:var(--surface)}
.type-badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:11px;font-weight:700;background:#ede9fe;color:#6d28d9}
.role-badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:10px;font-weight:700;background:#e2e8f0;color:var(--ink-2);text-transform:uppercase}

@media(max-width:768px){.sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}.content{margin-left:0}.page{padding:16px}.stat-grid{grid-template-columns:1fr 1fr}}
</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 active"><i class="fas fa-umbrella-beach"></i> Leave Approval</a></li>
      <li class="nav-item"><a href="mdmobile.php"                   class="nav-link"><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>Leave</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">MD Approval</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">Leave Approval Dashboard</div>
    <div class="page-subtitle">Review and manage employee leave requests</div>

    <!-- Stat Cards -->
    <div class="stat-grid">
      <div class="stat-card stat-pend">
        <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
        <div class="stat-num"><?= (int)($countData['pending_count']??0) ?></div>
        <div class="stat-lbl">Pending</div>
      </div>
      <div class="stat-card stat-appr">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div class="stat-num"><?= (int)($countData['approved_count']??0) ?></div>
        <div class="stat-lbl">Approved</div>
      </div>
      <div class="stat-card stat-rej">
        <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
        <div class="stat-num"><?= (int)($countData['rejected_count']??0) ?></div>
        <div class="stat-lbl">Rejected</div>
      </div>
    </div>

    <!-- Tabs -->
    <div class="tabs-wrap">
      <a href="?status=Pending"  class="tab-btn <?= $status_filter==='Pending' ?'active':'' ?>"><i class="fas fa-hourglass-half"></i> Pending</a>
      <a href="?status=Approved" class="tab-btn <?= $status_filter==='Approved'?'active':'' ?>"><i class="fas fa-check-circle"></i> Approved</a>
      <a href="?status=Rejected" class="tab-btn <?= $status_filter==='Rejected'?'active':'' ?>"><i class="fas fa-times-circle"></i> Rejected</a>
    </div>

    <!-- Table -->
    <div class="card">
      <div class="tbl-wrap">
        <table>
          <thead>
            <tr>
              <th>Employee</th>
              <th>Role</th>
              <th>Leave Type</th>
              <th>Date / Time</th>
              <th>Reason</th>
              <th>Work Description</th>
              <th>MD Comment</th>
              <?php if ($status_filter === 'Pending'): ?>
              <th style="width:130px">Action</th>
              <?php else: ?>
              <th>Applied On</th>
              <?php endif; ?>
            </tr>
          </thead>
          <tbody>
            <?php if ($result->num_rows === 0): ?>
            <tr><td colspan="8" class="empty-cell"><i class="fas fa-inbox"></i>No <?= htmlspecialchars($status_filter) ?> leave requests.</td></tr>
            <?php else: ?>
            <?php while ($row = $result->fetch_assoc()): ?>
            <tr>
              <form method="POST" action="md_leave_action.php">
              <td style="font-weight:600"><?= htmlspecialchars($row['username']??'') ?></td>
              <td><span class="role-badge"><?= strtoupper(htmlspecialchars($row['role']??'')) ?></span></td>
              <td><span class="type-badge"><?= htmlspecialchars($row['leave_type']??'') ?></span></td>
              <td style="white-space:nowrap">
                <?php if (($row['leave_type']??'') === 'Permission'): ?>
                  <?= htmlspecialchars($row['permission_date']??'') ?><br>
                  <span style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($row['permission_time_from']??'') ?> – <?= htmlspecialchars($row['permission_time_to']??'') ?> (<?= htmlspecialchars($row['permission_hours']??'') ?> hrs)</span>
                <?php else: ?>
                  <?= htmlspecialchars($row['start_date']??'') ?> <span style="color:var(--muted)">→</span> <?= htmlspecialchars($row['end_date']??'') ?>
                <?php endif; ?>
              </td>
              <td style="font-size:12px"><?= htmlspecialchars($row['reason']??'') ?></td>
              <td style="font-size:12px"><?= htmlspecialchars($row['work_description']??'') ?></td>
              <?php if ($status_filter === 'Pending'): ?>
              <td>
                <input type="hidden" name="leave_id" value="<?= (int)$row['id'] ?>">
                <textarea name="md_comment" class="comment-box" placeholder="Enter comment…" required></textarea>
              </td>
              <td>
                <button type="submit" name="action" value="approve" class="btn-approve"><i class="fas fa-check"></i> Approve</button>
                <button type="submit" name="action" value="reject"  class="btn-reject"><i class="fas fa-times"></i> Reject</button>
              </td>
              <?php else: ?>
              <td style="font-size:12px">
                <?= !empty($row['md_comment']) ? htmlspecialchars($row['md_comment']) : '<span style="color:var(--muted)"><em>No comment</em></span>' ?>
              </td>
              <td style="font-size:12px;color:var(--muted)"><?= htmlspecialchars($row['applied_on']??'') ?></td>
              <?php endif; ?>
              </form>
            </tr>
            <?php endwhile; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

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

<script>
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
</script>
</body>
</html>