<?php
require_once __DIR__ . '/auth.php';
ensureAdminAuth();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/discipline_system.php';
$db = (new Database())->getConnection();
discEnsureTables($db);
$adminId = (int)($_SESSION['admin_id'] ?? 0);
$senderRole = 'admin';
$recordType = 'warning';
$title = discPageTitle($recordType);
$recipients = discAllowedRecipients($db, $adminId, $senderRole);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_record'])) {
            discCreate($db, $adminId, $senderRole, $recordType, (int)($_POST['recipient_id'] ?? 0), $_POST['title'] ?? '', $_POST['message'] ?? '', $_POST['severity'] ?? 'normal');
            $_SESSION['flash_message'] = $title . ' sent successfully.';
        }
    } catch (Throwable $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
    header('Location: warning.php');
    exit;
}

$sent = discListSentByRole($db, $adminId, $senderRole, $recordType, 250);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= disc_h($title) ?> - Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&family=Space+Grotesk:wght@600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/ushs-global-theme.css">
<link rel="stylesheet" href="../assets/admin-sidebar.css">
<style>
:root{--admin-bg-1:#080240;--admin-bg-2:#093349;--admin-card-1:#17295e;--admin-card-2:#102448;--admin-border:rgba(96,165,250,.24);--admin-cyan:#17bdd4;--admin-text:#f8fafc;--admin-muted:#aebbd4;--admin-yellow:#facc15;--admin-red:#f43f5e;--admin-input:rgba(8,20,48,.72)}
body{background:linear-gradient(135deg,var(--admin-bg-1) 0%,var(--admin-bg-2) 100%) fixed!important;color:var(--admin-text)!important;font-family:Montserrat,Arial,sans-serif;min-height:100vh}.main-content{padding:96px 24px 32px}.disc-wrap{display:grid;grid-template-columns:minmax(320px,430px) 1fr;gap:16px}.disc-card{background:linear-gradient(135deg,var(--admin-card-1),var(--admin-card-2));border:1px solid var(--admin-border);border-radius:18px;padding:18px;margin-bottom:12px;box-shadow:0 18px 38px rgba(0,0,0,.22)}.disc-title{font-family:'Space Grotesk',Montserrat,sans-serif;font-weight:900}.disc-meta{color:var(--admin-muted);font-size:.8rem;margin-top:4px}.disc-msg{white-space:pre-wrap;margin-top:10px;line-height:1.55}.disc-empty{text-align:center;padding:28px;border:1px dashed var(--admin-border);border-radius:14px;color:var(--admin-muted)}.disc-badge{border:1px solid var(--admin-border);border-radius:999px;padding:4px 9px;font-size:.7rem;font-weight:900}.disc-high{color:var(--admin-red)}.disc-normal{color:var(--admin-yellow)}.disc-low{color:var(--admin-cyan)}.form-control,.form-select{background:var(--admin-input)!important;border:1px solid var(--admin-border)!important;color:#fff!important;border-radius:12px}.form-control::placeholder{color:rgba(226,232,240,.55)!important}.form-select option{background:#0f172a;color:#fff}.btn-primary{background:linear-gradient(135deg,#0ea5e9,#2563eb)!important;border:0!important;border-radius:12px;font-weight:900}.admin-note{color:var(--admin-muted)}@media(max-width:920px){.main-content{padding-left:14px;padding-right:14px}.disc-wrap{grid-template-columns:1fr}}
</style>
</head>
<body>
<?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar('warning.php'); ?>
<main class="main-content">
  <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3">
    <div>
      <h2 style="font-family:'Space Grotesk';font-weight:900;margin:0;"><i class="<?= discIcon($recordType) ?> me-2" style="color:<?= discColor($recordType) ?>"></i><?= disc_h($title) ?></h2>
      <div class="admin-note">Admin can send to CSR Managers, Team Leaders, and Agents.</div>
    </div>
  </div>

  <?php if (!empty($_SESSION['flash_message'])): ?><div class="alert alert-success"><?= disc_h($_SESSION['flash_message']); unset($_SESSION['flash_message']); ?></div><?php endif; ?>
  <?php if (!empty($_SESSION['flash_error'])): ?><div class="alert alert-danger"><?= disc_h($_SESSION['flash_error']); unset($_SESSION['flash_error']); ?></div><?php endif; ?>

  <div class="disc-wrap">
    <div>
      <div class="disc-card">
        <h5 class="disc-title mb-3">New <?= disc_h($title) ?></h5>
        <?php if(!$recipients): ?>
          <div class="disc-empty">No active CSR users found.</div>
        <?php else: ?>
        <form method="post">
          <label class="form-label">Send to</label>
          <select class="form-select mb-3" name="recipient_id" required>
            <?php foreach($recipients as $u): ?>
              <option value="<?= (int)$u['id'] ?>"><?= disc_h(discName($u)) ?> — <?= disc_h(discRoleLabel($u['role'] ?? 'csr')) ?><?= !empty($u['team_name']) ? ' / ' . disc_h($u['team_name']) : '' ?></option>
            <?php endforeach; ?>
          </select>
          <label class="form-label">Title</label>
          <input class="form-control mb-3" name="title" maxlength="180" placeholder="<?= disc_h($title) ?> title">
          <label class="form-label">Details</label>
          <textarea class="form-control mb-3" name="message" required rows="6" placeholder="Write details..."></textarea>
          <label class="form-label">Level</label>
          <select class="form-select mb-3" name="severity"><option value="low">Low</option><option value="normal" selected>Normal</option><option value="high">High</option></select>
          <button class="btn btn-primary w-100" name="create_record" value="1"><i class="fas fa-paper-plane me-1"></i>Send <?= disc_h($title) ?></button>
        </form>
        <?php endif; ?>
      </div>
    </div>

    <div>
      <div class="disc-card">
        <h5 class="disc-title mb-3">Sent by Admin</h5>
        <?php if(!$sent): ?><div class="disc-empty">No sent <?= strtolower(disc_h($title)) ?> yet.</div><?php endif; ?>
        <?php foreach($sent as $r): ?>
          <div class="disc-card" style="background:rgba(8,20,48,.55)">
            <div class="d-flex justify-content-between align-items-start gap-2 flex-wrap"><div><div class="disc-title"><?= disc_h($r['title']) ?></div><div class="disc-meta">To <?= disc_h(trim($r['recipient_name']) ?: $r['recipient_email']) ?> • <?= disc_h(discRoleLabel($r['recipient_role'])) ?><?= !empty($r['team_name']) ? ' • '.disc_h($r['team_name']) : '' ?> • <?= date('M j, Y g:i A', strtotime($r['created_at'])) ?></div></div><span class="disc-badge disc-<?= disc_h($r['severity']) ?>"><?= strtoupper(disc_h($r['severity'])) ?></span></div>
            <div class="disc-msg"><?= nl2br(disc_h($r['message'])) ?></div>
            <div class="disc-meta mt-2"><?= !empty($r['is_read']) ? '<i class="fas fa-check me-1"></i>Read' : '<i class="fas fa-clock me-1"></i>Unread' ?></div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
