<?php
require_once __DIR__ . '/../app/csrf.php';
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/audit.php';

$me  = require_role(['ADMIN']); // مدير النظام فقط يعتمد/يرفض التالف
$pdo = db();

$status = $_GET['status'] ?? 'PENDING';
$allowed = ['PENDING','APPROVED','REJECTED','ALL'];
if (!in_array($status, $allowed, true)) $status = 'PENDING';

$pageError = '';
$pageSuccess = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $op = $_POST['op'] ?? '';
  $id = (int)($_POST['id'] ?? 0);
  $reason = trim((string)($_POST['reason'] ?? ''));
  if ($id <= 0 || !in_array($op, ['approve','reject'], true)) {
    $pageError = 'طلب غير صالح.';
  } else {
    try {
      $pdo->beginTransaction();
      $st = $pdo->prepare("SELECT * FROM damage_reports WHERE id=? FOR UPDATE");
      $st->execute([$id]);
      $dr = $st->fetch();
      if (!$dr) {
        throw new Exception('لم يتم العثور على السجل.');
      }
      if ($dr['status'] !== 'PENDING') {
        throw new Exception('هذا الطلب تمت مراجعته مسبقاً.');
      }

      if ($op === 'approve') {
        $pdo->prepare("UPDATE damage_reports
                       SET status='APPROVED', admin_reason=?, approved_by=?, approved_at=NOW()
                       WHERE id=?")->execute([$reason !== '' ? $reason : null, (int)$me['id'], $id]);
        audit_log($pdo, (int)$me['id'], 'APPROVE', 'damage_reports', $id, ['reason'=>$reason]);
        $pageSuccess = 'تم اعتماد التالف بنجاح.';
      } else {
        $pdo->prepare("UPDATE damage_reports
                       SET status='REJECTED', admin_reason=?, approved_by=?, approved_at=NOW()
                       WHERE id=?")->execute([$reason !== '' ? $reason : null, (int)$me['id'], $id]);
        audit_log($pdo, (int)$me['id'], 'REJECT', 'damage_reports', $id, ['reason'=>$reason]);
        $pageSuccess = 'تم رفض التالف بنجاح. سيتم اعتباره على عهدة الموزع.';
      }

      $pdo->commit();
      redirect('damage_reports.php?status=PENDING');
    } catch (Throwable $e) {
      if ($pdo->inTransaction()) $pdo->rollBack();
      $pageError = 'خطأ: ' . $e->getMessage();
    }
  }
}

$where = "";
$params = [];
if ($status !== 'ALL') {
  $where = "WHERE dr.status = ?";
  $params[] = $status;
}

$st = $pdo->prepare("
  SELECT
    dr.*,
    i.issue_number, i.issue_month, i.issue_year,
    p.name AS product_name,
    d.name AS distributor_name,
    o.name AS outlet_name,
    u.name AS created_by_name,
    au.name AS approved_by_name
  FROM damage_reports dr
  JOIN issues i ON i.id = dr.issue_id
  JOIN products p ON p.id = i.product_id
  JOIN distributors d ON d.id = dr.distributor_id
  LEFT JOIN outlets o ON o.id = dr.outlet_id
  LEFT JOIN users u ON u.id = dr.created_by
  LEFT JOIN users au ON au.id = dr.approved_by
  $where
  ORDER BY dr.created_at DESC
  LIMIT 300
");
$st->execute($params);
$rows = $st->fetchAll();

function status_badge($s) {
  if ($s === 'PENDING') return '<span class="badge b-warn">قيد المراجعة</span>';
  if ($s === 'APPROVED') return '<span class="badge b-ok">معتمد</span>';
  if ($s === 'REJECTED') return '<span class="badge b-no">مرفوض</span>';
  return '<span class="badge">'.h($s).'</span>';
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>طلبات التالف — MGZ</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=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body{font-family:'Tajawal',sans-serif;background:#f6f7fb;margin:0;color:#111827}
a{color:inherit}
.container{max-width:1200px;margin:24px auto;padding:0 14px}
.top{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}
.h1{font-size:1.25rem;font-weight:800}
.filters{display:flex;gap:8px;flex-wrap:wrap}
.chip{padding:8px 12px;border-radius:999px;background:#fff;border:1px solid #e5e7eb;text-decoration:none;font-weight:700;font-size:.9rem}
.chip.active{background:#111827;color:#fff;border-color:#111827}
.card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;box-shadow:0 8px 22px rgba(17,24,39,.06)}
.table{width:100%;border-collapse:collapse}
.table th,.table td{padding:10px 10px;border-bottom:1px solid #f0f2f6;vertical-align:top;font-size:.92rem}
.table th{background:#fafafa;font-weight:800}
.badge{display:inline-block;padding:4px 10px;border-radius:999px;font-size:.78rem;font-weight:800}
.b-warn{background:#fff7ed;color:#9a3412}
.b-ok{background:#ecfdf5;color:#065f46}
.b-no{background:#fef2f2;color:#991b1b}
.small{font-size:.82rem;color:#6b7280}
.actions{display:flex;gap:8px;flex-wrap:wrap}
.btn{border:1px solid #e5e7eb;background:#fff;padding:8px 10px;border-radius:10px;cursor:pointer;font-weight:800}
.btn.ok{background:#10b9811a;border-color:#10b98140}
.btn.no{background:#ef44441a;border-color:#ef444440}
.alert{padding:10px 12px;border-radius:12px;margin:10px 0;font-weight:700}
.alert.ok{background:#ecfdf5;color:#065f46;border:1px solid #10b98140}
.alert.no{background:#fef2f2;color:#991b1b;border:1px solid #ef444440}
.reason{width:100%;min-width:180px;max-width:280px}
.img{width:56px;height:56px;border-radius:12px;object-fit:cover;border:1px solid #e5e7eb}
@media (max-width:900px){.hide-md{display:none}}
</style>
</head>
<body>
<div class="container">
  <div class="top">
    <div>
      <div class="h1">🧾 طلبات التالف (اعتماد المدير)</div>
      <div class="small">التالف لا يُقفل إلا بصورته واعتماد المدير. عند الرفض يُعتبر على عهدة الموزع.</div>
    </div>
    <div class="actions">
      <a class="btn" href="../dashboard.php">⬅️ لوحة التحكم</a>
    </div>
  </div>

  <?php if ($pageSuccess): ?><div class="alert ok"><?= h($pageSuccess) ?></div><?php endif; ?>
  <?php if ($pageError): ?><div class="alert no"><?= h($pageError) ?></div><?php endif; ?>

  <div class="filters">
    <?php foreach (['PENDING'=>'قيد المراجعة','APPROVED'=>'معتمد','REJECTED'=>'مرفوض','ALL'=>'الكل'] as $k=>$lbl): ?>
      <a class="chip <?= $status===$k?'active':'' ?>" href="?status=<?= h($k) ?>"><?= h($lbl) ?></a>
    <?php endforeach; ?>
  </div>

  <div class="card" style="margin-top:12px;overflow:auto;">
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>الصورة</th>
          <th>الإصدار</th>
          <th>الموزع / المنفذ</th>
          <th class="hide-md">الموقع</th>
          <th>الكمية</th>
          <th>الحالة</th>
          <th class="hide-md">التاريخ</th>
          <th>إجراء</th>
        </tr>
      </thead>
      <tbody>
      <?php if (empty($rows)): ?>
        <tr><td colspan="9" class="small" style="padding:16px;">لا توجد سجلات.</td></tr>
      <?php else: foreach ($rows as $r): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td>
            <?php $img = (string)$r['photo_path']; ?>
            <?php if ($img): ?>
              <a href="<?= h($img) ?>" target="_blank" rel="noopener">
                <img class="img" src="<?= h($img) ?>" alt="damage">
              </a>
            <?php else: ?>—<?php endif; ?>
          </td>
          <td>
            <div style="font-weight:900"><?= h($r['product_name']) ?></div>
            <div class="small">عدد <?= h($r['issue_number'] ?? '') ?> — <?= sprintf('%02d/%d',(int)$r['issue_month'],(int)$r['issue_year']) ?></div>
          </td>
          <td>
            <div style="font-weight:900"><?= h($r['distributor_name']) ?></div>
            <div class="small"><?= $r['outlet_name'] ? ('منفذ: '.h($r['outlet_name'])) : '—' ?></div>
          </td>
          <td class="hide-md"><?= $r['location']==='WITH_OUTLET'?'عند المنفذ':'مع الموزع' ?></td>
          <td style="font-weight:900"><?= (int)$r['qty'] ?></td>
          <td><?= status_badge($r['status']) ?></td>
          <td class="hide-md"><div class="small"><?= h($r['created_at']) ?></div></td>
          <td>
            <?php if ($r['status']==='PENDING'): ?>
              <form method="post" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                <?= csrf_field() ?>
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <input class="reason" type="text" name="reason" placeholder="سبب/ملاحظة (اختياري)">
                <button class="btn ok" name="op" value="approve">اعتماد</button>
                <button class="btn no" name="op" value="reject">رفض</button>
              </form>
            <?php else: ?>
              <div class="small">تمت المراجعة بواسطة: <?= h($r['approved_by_name'] ?: '—') ?></div>
              <div class="small">ملاحظة: <?= h($r['admin_reason'] ?: '—') ?></div>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
</body>
</html>
