<?php
require_once __DIR__ . '/../app/csrf.php';
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/csrf.php';

$me = require_role(['ADMIN']);
$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $name = trim($_POST['name'] ?? '');
  $type = $_POST['comm_type'] ?? 'PERCENT';
  $val  = (float)($_POST['comm_val'] ?? 0);

  if ($name !== '') {
    $st = $pdo->prepare("INSERT INTO distributors (name, commission_type, commission_value, active) VALUES (?,?,?,1)");
    $st->execute([$name, $type, $val]);
    redirect("distributors.php");
  }
}

$rows = $pdo->query("SELECT * FROM distributors ORDER BY name")->fetchAll();
$csrf = csrf_token();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>الموزعون — MGZ</title>
<style>
  /* ======= Reset & Base ======= */
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
    background: #f3f4f6;
    color: #1f2937;
    min-height: 100vh;
  }

  /* ======= Back Link ======= */
  .back-link {
    display: inline-block;
    padding: 10px 20px;
    color: #6b7280;
    text-decoration: none;
    font-size: 0.9rem;
    transition: color .2s;
  }
  .back-link:hover { color: #1d4ed8; }

  /* ======= Page Header ======= */
  .page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2563eb 100%);
    color: #fff;
    padding: 22px 32px;
    border-radius: 12px;
    margin: 0 20px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 4px 15px rgba(37,99,235,.35);
  }
  .page-header h1 {
    font-size: 1.6rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .page-header .subtitle {
    font-size: 0.85rem;
    opacity: .8;
    margin-top: 4px;
  }

  /* ======= Content ======= */
  .content { padding: 0 20px 40px; }

  /* ======= Card ======= */
  .card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 24px;
    overflow: hidden;
  }
  .card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #e5e7eb;
    font-size: 1rem;
    font-weight: 600;
    color: #1e3a5f;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .card-body { padding: 24px; }

  /* ======= Form ======= */
  .form-row {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
  .form-row input[type="text"],
  .form-row input[type="number"],
  .form-row select {
    padding: 9px 14px;
    border: 1px solid #d1d5db;
    border-radius: 7px;
    font-size: 0.95rem;
    font-family: inherit;
    background: #f9fafb;
    color: #1f2937;
    transition: border-color .2s, box-shadow .2s;
    outline: none;
  }
  .form-row input[type="text"]   { width: 220px; }
  .form-row input[type="number"] { width: 130px; }
  .form-row input:focus,
  .form-row select:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37,99,235,.15);
    background: #fff;
  }
  .form-row label {
    font-size: 0.82rem;
    color: #6b7280;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  .btn-add {
    background: #2563eb;
    color: #fff;
    border: none;
    padding: 9px 22px;
    border-radius: 7px;
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: background .2s, transform .1s;
    align-self: flex-end;
  }
  .btn-add:hover  { background: #1d4ed8; }
  .btn-add:active { transform: scale(.98); }

  /* ======= Table ======= */
  .table-meta {
    font-size: 0.85rem;
    color: #6b7280;
    padding: 12px 24px 0;
  }
  table { width: 100%; border-collapse: collapse; }
  thead th {
    background: #f1f5f9;
    color: #374151;
    font-weight: 600;
    font-size: 0.875rem;
    padding: 12px 18px;
    text-align: right;
    border-bottom: 2px solid #e5e7eb;
  }
  tbody tr {
    border-bottom: 1px solid #f3f4f6;
    transition: background .15s;
  }
  tbody tr:hover  { background: #f8faff; }
  tbody tr:last-child { border-bottom: none; }
  tbody td {
    padding: 13px 18px;
    font-size: 0.9rem;
    color: #374151;
    text-align: right;
  }

  /* ======= Badges ======= */
  .badge {
    display: inline-block;
    padding: 3px 11px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
  }
  .badge-active    { background: #d1fae5; color: #065f46; }
  .badge-inactive  { background: #fee2e2; color: #991b1b; }
  .badge-percent   { background: #ede9fe; color: #4c1d95; }
  .badge-per-copy  { background: #dbeafe; color: #1e40af; }
  .badge-none      { background: #f3f4f6; color: #6b7280; }

  /* ======= Commission Value ======= */
  .comm-value {
    font-weight: 700;
    color: #1e3a5f;
  }
  .comm-unit {
    font-size: 0.78rem;
    color: #6b7280;
    margin-right: 3px;
  }

  /* ======= Empty State ======= */
  .empty-state {
    text-align: center;
    padding: 50px 20px;
    color: #9ca3af;
  }
  .empty-state .icon { font-size: 2.5rem; margin-bottom: 12px; }
  .empty-state p { font-size: 0.95rem; }
</style>
</head>
<body>

<a class="back-link" href="../dashboard.php">→ العودة للرئيسية</a>

<!-- Page Header -->
<div class="page-header">
  <div>
    <h1>🚚 إدارة الموزعين</h1>
    <div class="subtitle">إضافة وعرض موزعي المجلات وعمولاتهم</div>
  </div>
  <div style="font-size:2.2rem; opacity:.2;">🚚</div>
</div>

<div class="content">

  <!-- Add Form Card -->
  <div class="card">
    <div class="card-header">➕ إضافة موزع جديد</div>
    <div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <div class="form-row">

          <label>
            اسم الموزع
            <input
              type="text"
              name="name"
              placeholder="مثال: أحمد محمد"
              required
              aria-label="اسم الموزع"
            >
          </label>

          <label>
            نوع العمولة
            <select name="comm_type" aria-label="نوع العمولة">
              <option value="PERCENT">نسبة مئوية (%)</option>
              <option value="PER_COPY">مبلغ لكل نسخة</option>
              <option value="NONE">بدون عمولة</option>
            </select>
          </label>

          <label>
            قيمة العمولة
            <input
              type="number"
              name="comm_val"
              step="0.001"
              min="0"
              placeholder="0.000"
              aria-label="قيمة العمولة"
            >
          </label>

          <button type="submit" class="btn-add">✔ إضافة</button>

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

  <!-- List Card -->
  <div class="card">
    <div class="card-header">🚚 قائمة الموزعين</div>
    <div class="table-meta"><?= count($rows) ?> موزع</div>

    <?php if (empty($rows)): ?>
      <div class="empty-state">
        <div class="icon">🚚</div>
        <p>لا يوجد موزعون مسجلون بعد</p>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>اسم الموزع</th>
          <th>نوع العمولة</th>
          <th>قيمة العمولة</th>
          <th>الحالة</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $i => $r): ?>
        <tr>
          <td><?= $i + 1 ?></td>
          <td><strong><?= h($r['name']) ?></strong></td>
          <td>
            <?php if ($r['commission_type'] === 'PERCENT'): ?>
              <span class="badge badge-percent">نسبة مئوية</span>
            <?php elseif ($r['commission_type'] === 'PER_COPY'): ?>
              <span class="badge badge-per-copy">لكل نسخة</span>
            <?php else: ?>
              <span class="badge badge-none">بدون عمولة</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($r['commission_type'] !== 'NONE'): ?>
              <span class="comm-value"><?= number_format((float)$r['commission_value'], 3) ?></span>
              <?php if ($r['commission_type'] === 'PERCENT'): ?>
                <span class="comm-unit">%</span>
              <?php else: ?>
                <span class="comm-unit">ر.ع. / نسخة</span>
              <?php endif; ?>
            <?php else: ?>
              <span style="color:#9ca3af;">—</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($r['active']): ?>
              <span class="badge badge-active">نشط</span>
            <?php else: ?>
              <span class="badge badge-inactive">متوقف</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

</div><!-- /content -->
</body>
</html>
