<?php
// csr/mistake.php — Mistake page
if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['csr_id'])) { header('Location: ../login.php'); exit; }
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/discipline_system.php';
$db = (new Database())->getConnection();
discEnsureTables($db);
$meId = (int)$_SESSION['csr_id'];
$me = discUser($db, $meId);
if (!$me) { header('Location: logout.php'); exit; }
$role = $me['role'] ?? 'csr';
$recordType = 'mistake';
$title = discPageTitle($recordType);
$canSend = discCanSend($role, $recordType);
$recipients = $canSend ? discAllowedRecipients($db, $meId, $role) : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_record'])) {
            discCreate($db, $meId, $role, $recordType, (int)($_POST['recipient_id'] ?? 0), $_POST['title'] ?? '', $_POST['message'] ?? '', $_POST['severity'] ?? 'normal');
            $_SESSION['flash_message'] = $title . ' sent successfully.';
        } elseif (isset($_POST['mark_read'])) {
            discMarkRead($db, (int)($_POST['record_id'] ?? 0), $meId);
            $_SESSION['flash_message'] = $title . ' marked as read.';
        }
    } catch (Throwable $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
    header('Location: mistake.php'); exit;
}

$sent = $canSend ? discListSent($db, $meId, $recordType, 180) : [];
$received = discListReceived($db, $meId, $recordType, 180);

ob_start();
?>
<style>
.disc-wrap{display:grid;grid-template-columns:minmax(320px,430px) 1fr;gap:16px}.disc-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:16px;padding:16px;margin-bottom:12px}.disc-title{font-family:'Space Grotesk';font-weight:900}.disc-meta{color:var(--cm-muted);font-size:.78rem;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(--cm-border);border-radius:14px;color:var(--cm-muted)}.disc-badge{border:1px solid var(--cm-border);border-radius:999px;padding:4px 9px;font-size:.7rem;font-weight:900}.disc-high{color:var(--cm-red)}.disc-normal{color:var(--cm-yellow)}.disc-low{color:var(--cm-cyan)}@media(max-width:920px){.disc-wrap{grid-template-columns:1fr}}
</style>
<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="text-muted"><?php if($role==='csr_manager'): ?>Send to Team Leaders or Agents.<?php elseif($role==='team_leader'): ?>Send to Agents inside your team.<?php else: ?>View your own <?= strtolower(disc_h($title)) ?> records.<?php endif; ?></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>
    <?php if($canSend): ?>
    <div class="disc-card">
      <h5 class="disc-title mb-3">New <?= disc_h($title) ?></h5>
      <?php if(!$recipients): ?>
        <div class="disc-empty">No allowed recipients 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>
    <?php endif; ?>

    <div class="disc-card">
      <h5 class="disc-title mb-3">For Me</h5>
      <?php if(!$received): ?><div class="disc-empty">No <?= strtolower(disc_h($title)) ?> records.</div><?php endif; ?>
      <?php foreach($received as $r): ?>
        <div class="border-bottom pb-3 mb-3" style="border-color:var(--cm-border)!important">
          <div class="d-flex justify-content-between gap-2 flex-wrap"><div class="disc-title"><?= disc_h($r['title']) ?></div><span class="disc-badge disc-<?= disc_h($r['severity']) ?>"><?= strtoupper(disc_h($r['severity'])) ?></span></div>
          <div class="disc-meta">From <?= disc_h(trim($r['sender_name']) ?: $r['sender_email']) ?> • <?= disc_h(discRoleLabel($r['sender_role'])) ?> • <?= date('M j, Y g:i A', strtotime($r['created_at'])) ?></div>
          <div class="disc-msg"><?= nl2br(disc_h($r['message'])) ?></div>
          <?php if(empty($r['is_read'])): ?><form method="post" class="mt-2"><input type="hidden" name="record_id" value="<?= (int)$r['id'] ?>"><button class="btn btn-sm btn-primary" name="mark_read" value="1">Read</button></form><?php else: ?><div class="disc-meta mt-2"><i class="fas fa-check me-1"></i>Read<?= !empty($r['read_at']) ? ' on '.date('M j, Y g:i A', strtotime($r['read_at'])) : '' ?></div><?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <div>
    <?php if($canSend): ?>
    <div class="disc-card">
      <h5 class="disc-title mb-3">Sent by Me</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:oklch(0.11 0.032 261/.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>
    <?php endif; ?>
  </div>
</div>
<?php $content = ob_get_clean(); require_once __DIR__ . '/layout.php'; ?>
