<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (!file_exists('config.php')) {
    die("Configuration file not found. Please contact the administrator.");
}
include 'config.php';

if ($conn->connect_error) {
    die("Unable to connect to the database. Please contact the administrator.");
}

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

$user_id  = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Unknown User';

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

$error   = null;
$success = false;

/* ── SUBMIT ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title       = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if (empty($title) || empty($description)) {
        $error = "Please fill in all fields.";
    } else {
        $sql  = "INSERT INTO grievances (user_id, title, description, status, created_at) VALUES (?, ?, ?, 'Pending', NOW())";
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            $error = "Error preparing submission. Please try again later.";
        } else {
            $stmt->bind_param("sss", $user_id, $title, $description);
            if ($stmt->execute()) {
                $success = true;
            } else {
                $error = "Error submitting grievance. Please try again later.";
            }
            $stmt->close();
        }
    }
}

/* ── FETCH GRIEVANCES ── */
$grievance_error = null;
$grievances      = [];

$check = $conn->query("SHOW TABLES LIKE 'grievances'");
if (!$check || $check->num_rows === 0) {
    $grievance_error = "Grievances table not found in the database.";
} else {
    $sql  = "SELECT id, title, description, status, hr_reply, created_at FROM grievances WHERE user_id = ? ORDER BY created_at DESC";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        $grievance_error = "Unable to prepare query. Please try again later.";
    } else {
        $stmt->bind_param("s", $user_id);
        if (!$stmt->execute()) {
            $grievance_error = "Unable to fetch grievances. Please try again later.";
        } else {
            $res = $stmt->get_result();
            while ($r = $res->fetch_assoc()) $grievances[] = $r;
        }
        $stmt->close();
    }
}

/* ── STATS ── */
$total    = count($grievances);
$pending  = count(array_filter($grievances, fn($r) => $r['status'] === 'Pending'));
$review   = count(array_filter($grievances, fn($r) => $r['status'] === 'In Review'));
$resolved = count(array_filter($grievances, fn($r) => $r['status'] === 'Resolved'));

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · Grievance</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&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:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}

/* ═══ SIDEBAR ═══ */
.sidebar{
  width:var(--sidebar-w);background:var(--sidebar-bg);
  position:fixed;inset:0 auto 0 0;z-index:300;
  display:flex;flex-direction:column;overflow-y:auto;
  transition:transform .28s cubic-bezier(.4,0,.2,1);
  scrollbar-width:none;
}
.sidebar::-webkit-scrollbar{display:none}
.sidebar-brand{padding:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:9px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:16px;text-align:center;font-size:13px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:12px 8px;border-top:1px solid rgba(255,255,255,.06)}
.sidebar-user-info{display:flex;align-items:center;gap:10px;padding:10px 14px;margin:0 8px 4px;border-radius:8px;background:rgba(255,255,255,.04)}
.sidebar-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700;flex-shrink:0}
.sidebar-uname{font-size:12px;font-weight:600;color:rgba(255,255,255,.8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sidebar-role{font-size:10px;color:rgba(255,255,255,.35);text-transform:uppercase;letter-spacing:.8px}

/* ═══ OVERLAY ═══ */
.sidebar-overlay{
  display:none;position:fixed;inset:0;
  background:rgba(0,0,0,.55);z-index:290;
  backdrop-filter:blur(2px);opacity:0;transition:opacity .28s;
}
.sidebar-overlay.active{display:block;opacity:1}

/* ═══ CONTENT ═══ */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column}
.topbar{height:56px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 18px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:36px;height:36px;border-radius:8px;border:1px solid var(--border);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:15px;flex-shrink:0;transition:background .15s}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);overflow:hidden}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px;white-space:nowrap}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500;flex-shrink:0}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}

/* ═══ PAGE ═══ */
.page{padding:18px;flex:1;max-width:100%}
.page-header{margin-bottom:18px;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:12px;color:var(--muted);margin-top:2px}

/* ═══ STAT CARDS ═══ */
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow);display:flex;align-items:center;gap:12px}
.stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0}
.stat-icon.blue{background:#dbeafe;color:#1d4ed8}
.stat-icon.green{background:#d1fae5;color:#059669}
.stat-icon.amber{background:#fef3c7;color:#d97706}
.stat-icon.cyan{background:#cffafe;color:#0891b2}
.stat-label{font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.stat-value{font-size:22px;font-weight:700;color:var(--ink);letter-spacing:-.5px;line-height:1.2}

/* ═══ DASH CARD ═══ */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:16px;overflow:hidden}
.dash-card-header{padding:14px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:13px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:12px}
.dash-card-body{padding:18px}

/* ═══ FORM ═══ */
.form-group{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}
.form-label{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.form-label span{color:var(--red);margin-left:2px}
.form-control{width:100%;padding:9px 12px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:14px;font-family:'DM Sans',sans-serif;color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s,background .15s;-webkit-appearance:none}
.form-control:focus{border-color:var(--accent);background:var(--surface);box-shadow:0 0 0 3px rgba(79,70,229,.08)}
.form-control::placeholder{color:var(--muted)}
textarea.form-control{resize:vertical;min-height:110px;line-height:1.6}
.section-divider{display:flex;align-items:center;gap:10px;margin:6px 0 12px}
.section-divider span{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);white-space:nowrap}
.section-divider::before,.section-divider::after{content:'';flex:1;height:1px;background:var(--border)}
.btn-submit{width:100%;padding:12px 20px;background:linear-gradient(135deg,var(--accent),#6366f1);color:#fff;border:none;border-radius:var(--radius-sm);font-size:14px;font-weight:700;font-family:'DM Sans',sans-serif;cursor:pointer;transition:opacity .15s,transform .15s;display:flex;align-items:center;justify-content:center;gap:8px;margin-top:8px}
.btn-submit:hover{opacity:.92;transform:translateY(-1px)}
.btn-submit:active{transform:translateY(0)}

/* ═══ ALERTS ═══ */
.alert-custom{padding:12px 14px;border-radius:var(--radius-sm);font-size:13px;margin-bottom:14px;display:flex;align-items:flex-start;gap:10px}
.alert-success-custom{background:#d1fae5;border-left:3px solid var(--green);color:#065f46}
.alert-error-custom{background:#fee2e2;border-left:3px solid var(--red);color:#991b1b}

/* ═══ TABLE ═══ */
.tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
.dash-table{width:100%;border-collapse:collapse;font-size:12.5px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:10px;text-transform:uppercase;letter-spacing:.6px;padding:10px 12px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:10px 12px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:top}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}

/* ═══ BADGES ═══ */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:10.5px;font-weight:600;white-space:nowrap}
.badge-success{background:#d1fae5;color:#065f46}
.badge-warning{background:#fef3c7;color:#92400e}
.badge-cyan{background:#cffafe;color:#155e75}

/* ═══ HR REPLY BOX ═══ */
.reply-box{background:#f8fafc;border:1px solid var(--border);border-radius:var(--radius-sm);padding:9px 11px;font-size:11.5px;color:var(--ink-2);line-height:1.6}
.reply-box .reply-label{font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--accent);margin-bottom:3px}

/* ═══ EMPTY ═══ */
.empty-state{text-align:center;padding:40px 24px;color:var(--muted)}
.empty-state i{font-size:32px;display:block;margin-bottom:10px;opacity:.3}

/* ═══ BACK BTN ═══ */
.back-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-weight:600;color:var(--ink-2);text-decoration:none;box-shadow:var(--shadow);transition:background .15s;white-space:nowrap}
.back-btn:hover{background:var(--bg);color:var(--ink)}

/* ═══ RESPONSIVE ═══ */
@media(max-width:992px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .content{margin-left:0}
  .page{padding:14px}
  .stats-grid{grid-template-columns:repeat(2,1fr)}
  .page-header{flex-direction:column;gap:8px}
}
</style>
</head>
<body>

<!-- OVERLAY -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<div class="layout">

<!-- ═══ SIDEBAR ═══ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub">Employee</div>
    </div>
  </div>

  <div class="sidebar-user-info">
    <div class="sidebar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
    <div>
      <div class="sidebar-uname"><?= h($username) ?></div>
      <div class="sidebar-role">Employee</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_employee.php" class="nav-link"><i class="fas fa-gauge-high"></i> Dashboard</a></li>
  </ul>
  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="apply_leave.php" class="nav-link"><i class="fas fa-calendar-minus"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="expense.php" class="nav-link"><i class="fas fa-receipt"></i> Expenses</a></li>
    <li class="nav-item"><a href="tasks_employee.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="daily_report.php" class="nav-link"><i class="fas fa-file-lines"></i> Attendance &amp; Daily Report</a></li>
    <li class="nav-item"><a href="employee_grievance.php" class="nav-link active"><i class="fas fa-exclamation-triangle"></i> Grievance</a></li>
  </ul>

  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item">
        <a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')">
          <i class="fas fa-right-from-bracket"></i> Logout
        </a>
      </li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()" aria-label="Toggle menu">
      <i class="fas fa-bars"></i>
    </button>
    <div class="topbar-breadcrumb">
      <span>Employee</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span>Support</span>
      <i class="fas fa-chevron-right" style="font-size:8px;margin:0 2px;opacity:.5"></i>
      <span class="current">Grievance</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($username, 0, 1)) ?></div>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div>
        <div class="page-title">Grievance Portal</div>
        <div class="page-subtitle">Submit and track your grievances · sent to HR</div>
      </div>
      <a href="dashboard_employee.php" class="back-btn"><i class="fas fa-arrow-left" style="font-size:10px"></i> Dashboard</a>
    </div>

    <?php if ($success): ?>
      <div class="alert-custom alert-success-custom"><i class="fas fa-check-circle" style="flex-shrink:0"></i><span>Your grievance has been submitted successfully.</span></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-exclamation-circle" style="flex-shrink:0"></i><span><?= h($error) ?></span></div>
    <?php endif; ?>
    <?php if ($grievance_error): ?>
      <div class="alert-custom alert-error-custom"><i class="fas fa-exclamation-circle" style="flex-shrink:0"></i><span><?= h($grievance_error) ?></span></div>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-comment-dots"></i></div>
        <div><div class="stat-label">Total</div><div class="stat-value"><?= $total ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon amber"><i class="fas fa-hourglass-half"></i></div>
        <div><div class="stat-label">Pending</div><div class="stat-value"><?= $pending ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon cyan"><i class="fas fa-magnifying-glass"></i></div>
        <div><div class="stat-label">In Review</div><div class="stat-value"><?= $review ?></div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
        <div><div class="stat-label">Resolved</div><div class="stat-value"><?= $resolved ?></div></div>
      </div>
    </div>

    <!-- FORM -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-comment-medical"></i> Submit a Grievance</div>
        <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px">→ HR</span>
      </div>
      <div class="dash-card-body">
        <form method="POST">
          <div class="section-divider"><span>Grievance Details</span></div>

          <div class="form-group">
            <label class="form-label">Title <span>*</span></label>
            <input type="text" name="title" class="form-control" placeholder="Brief title of your grievance…" required>
          </div>

          <div class="form-group">
            <label class="form-label">Description <span>*</span></label>
            <textarea name="description" class="form-control" placeholder="Describe your grievance in detail…" required></textarea>
          </div>

          <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Submit Grievance</button>
        </form>
      </div>
    </div>

    <!-- HISTORY -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-history"></i> Submitted Grievances</div>
        <?php if (!empty($grievances)): ?>
          <span style="font-size:10px;font-weight:600;background:#dbeafe;color:#1e40af;padding:3px 9px;border-radius:20px"><?= count($grievances) ?> records</span>
        <?php endif; ?>
      </div>
      <div class="dash-card-body" style="padding:0">
        <?php if (empty($grievances)): ?>
          <div class="empty-state"><i class="fas fa-comment-slash"></i><p>No grievances submitted yet.</p></div>
        <?php else: ?>
          <div class="tbl-wrap">
            <table class="dash-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Title</th>
                  <th>Description</th>
                  <th>Status</th>
                  <th>HR Reply</th>
                  <th>Submitted</th>
                </tr>
              </thead>
              <tbody>
                <?php $i = 1; foreach ($grievances as $row): ?>
                  <?php
                    $st = $row['status'] ?? 'Pending';
                    $sc = $st === 'Resolved' ? 'badge-success' : ($st === 'In Review' ? 'badge-cyan' : 'badge-warning');
                    $si = $st === 'Resolved' ? 'fa-check-circle' : ($st === 'In Review' ? 'fa-magnifying-glass' : 'fa-hourglass-half');
                  ?>
                  <tr>
                    <td style="color:var(--muted);font-size:11px"><?= $i++ ?></td>
                    <td style="font-weight:600;max-width:140px;font-size:12px"><?= h($row['title']) ?></td>
                    <td style="max-width:200px;font-size:11px;color:var(--ink-2)"><?= nl2br(h(mb_strimwidth($row['description'], 0, 100, '…'))) ?></td>
                    <td><span class="badge-custom <?= $sc ?>"><i class="fas <?= $si ?>"></i> <?= h($st) ?></span></td>
                    <td style="min-width:140px">
                      <?php if (!empty($row['hr_reply'])): ?>
                        <div class="reply-box">
                          <div class="reply-label"><i class="fas fa-reply" style="margin-right:3px"></i>HR Response</div>
                          <?= nl2br(h($row['hr_reply'])) ?>
                        </div>
                      <?php else: ?>
                        <span style="font-size:11px;color:var(--muted);font-style:italic">No reply yet</span>
                      <?php endif; ?>
                    </td>
                    <td style="font-size:11px;color:var(--muted);white-space:nowrap"><?= h(date("d M Y", strtotime($row['created_at']))) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

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

<script>
function toggleSidebar() {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  if (sidebar.classList.contains('open')) {
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
  } else {
    sidebar.classList.add('open');
    overlay.classList.add('active');
  }
}
function closeSidebar() {
  document.getElementById('sidebar').classList.remove('open');
  document.getElementById('sidebarOverlay').classList.remove('active');
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSidebar(); });
</script>
</body>
</html>