<?php
// admin/partners.php
require_once "../config/db.php";
require_once "../includes/auth.php";
include "partials/header.php";
// TODO: تحقق من جلسة المشرف
// session_start(); if (empty($_SESSION['admin'])) { header('Location: login.php'); exit; }

/* ===== إنشاء الجدول إن لم يوجد ===== */
db()->exec("
CREATE TABLE IF NOT EXISTS partners (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(160) NOT NULL,
  logo VARCHAR(255) NOT NULL,
  url  VARCHAR(255) DEFAULT NULL,
  sort INT DEFAULT 0,
  status TINYINT(1) DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// بداية الجلسة بشكل آمن
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = $_SESSION['csrf'];

/* ===== ملف الرفع ===== */
function save_logo_upload(array $file): ?string {
  if (empty($file['name']) || $file['error'] !== UPLOAD_ERR_OK) return null;
  $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, ['png','jpg','jpeg','webp','svg'])) return null;
  $dir = __DIR__ . '/../uploads/partners';
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  $name = 'partner_' . date('Ymd_His') . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
  $dest = $dir . '/' . $name;
  if (!move_uploaded_file($file['tmp_name'], $dest)) return null;
  return 'uploads/partners/' . $name;
}

/* ===== عمليات إضافة/تعديل/حذف ===== */
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf']) && hash_equals($_SESSION['csrf'], $_POST['csrf'])) {
  $action = $_POST['action'] ?? '';
  if ($action === 'create') {
    $name = trim($_POST['name'] ?? '');
    $url  = trim($_POST['url'] ?? '');
    $sort = (int)($_POST['sort'] ?? 0);
    $status = (int)($_POST['status'] ?? 1);
    $logo = save_logo_upload($_FILES['logo'] ?? []);
    if ($name && $logo) {
      $st = db()->prepare("INSERT INTO partners (name, logo, url, sort, status) VALUES (?,?,?,?,?)");
      $st->execute([$name, $logo, $url, $sort, $status]);
      $msg = 'تم إضافة الشريك بنجاح.';
    } else {
      $msg = 'الاسم أو الشعار مفقود.';
    }
  }
  if ($action === 'update') {
    $id   = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $url  = trim($_POST['url'] ?? '');
    $sort = (int)($_POST['sort'] ?? 0);
    $status = (int)($_POST['status'] ?? 1);
    $logo = save_logo_upload($_FILES['logo'] ?? []);
    if ($id && $name) {
      if ($logo) {
        $st = db()->prepare("UPDATE partners SET name=?, logo=?, url=?, sort=?, status=? WHERE id=?");
        $st->execute([$name,$logo,$url,$sort,$status,$id]);
      } else {
        $st = db()->prepare("UPDATE partners SET name=?, url=?, sort=?, status=? WHERE id=?");
        $st->execute([$name,$url,$sort,$status,$id]);
      }
      $msg = 'تم تحديث بيانات الشريك.';
    }
  }
}
if (isset($_GET['delete'], $_GET['csrf']) && hash_equals($_SESSION['csrf'], $_GET['csrf'])) {
  $id = (int)$_GET['delete'];
  db()->prepare("DELETE FROM partners WHERE id=?")->execute([$id]);
  $msg = 'تم حذف الشريك.';
}

/* ===== جلب السجلات ===== */
$rows = db()->query("SELECT * FROM partners ORDER BY sort, id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>لوحة التحكم - شركاؤنا</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;800&display=swap');
*{box-sizing:border-box} body{margin:0;background:#0b0b0b;color:#eaeaea;font-family:'Cairo',system-ui}
.wrap{width:min(1100px,95%);margin:30px auto}
h1{margin:0 0 18px}
.card{background:#121212;border:1px solid rgba(212,175,55,.45);border-radius:14px;padding:16px;box-shadow:0 12px 26px rgba(0,0,0,.35);margin-bottom:18px}
input,select{width:100%;padding:10px 12px;border-radius:10px;border:1px solid rgba(212,175,55,.35);background:#0f0f0f;color:#fff}
label{display:block;margin:8px 0 6px}
.grid{display:grid;gap:12px;grid-template-columns:1fr 1fr}
@media (max-width:700px){.grid{grid-template-columns:1fr}}
.btn{padding:10px 16px;border-radius:10px;border:0;cursor:pointer;font-weight:800}
.btn-gold{background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#111}
.btn-dark{background:#1f2937;color:#eaeaea}
table{width:100%;border-collapse:collapse;margin-top:10px}
th,td{padding:10px;border-bottom:1px solid #232323;text-align:right}
th{color:#d4af37}
.badge{padding:4px 8px;border-radius:8px;background:#0f172a;border:1px solid #334155}
.msg{margin-bottom:10px;color:#b8f7c8;background:#0f2a17;border:1px solid #1d7a41;padding:8px 10px;border-radius:8px}
.actions a{margin-left:6px}
.logo{width:120px;height:60px;object-fit:contain;background:#0f0f0f;border:1px solid #333;border-radius:8px;padding:4px}
</style>
</head>
<body>
<div class="wrap">
  <h1><i class="fa-solid fa-handshake-angle"></i> إدارة شركاؤنا</h1>
  <?php if ($msg): ?><div class="msg"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

  <div class="card">
    <h3>إضافة شريك</h3>
    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="create">
      <div class="grid">
        <div>
          <label>اسم الشريك</label>
          <input name="name" required>
        </div>
        <div>
          <label>رابط الموقع (اختياري)</label>
          <input name="url" placeholder="https://...">
        </div>
      </div>
      <div class="grid">
        <div>
          <label>الترتيب</label>
          <input type="number" name="sort" value="0">
        </div>
        <div>
          <label>الحالة</label>
          <select name="status">
            <option value="1">مفعل</option>
            <option value="0">معطل</option>
          </select>
        </div>
      </div>
      <div style="margin-top:8px">
        <label>شعار الشريك (PNG/JPG/WEBP/SVG)</label>
        <input type="file" name="logo" accept=".png,.jpg,.jpeg,.webp,.svg" required>
      </div>
      <div style="margin-top:12px">
        <button class="btn btn-gold"><i class="fa-solid fa-plus"></i> إضافة</button>
      </div>
    </form>
  </div>

  <div class="card">
    <h3>القائمة</h3>
    <table>
      <thead>
        <tr>
          <th>#</th><th>الشعار</th><th>الاسم</th><th>الرابط</th><th>الترتيب</th><th>الحالة</th><th>تحكم</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $r): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td><img class="logo" src="../<?= htmlspecialchars($r['logo']) ?>" alt=""></td>
          <td><?= htmlspecialchars($r['name']) ?></td>
          <td><?= $r['url'] ? '<a target="_blank" href="'.htmlspecialchars($r['url']).'">فتح</a>' : '-' ?></td>
          <td><?= (int)$r['sort'] ?></td>
          <td><?= $r['status']?'مفعل':'معطل' ?></td>
          <td class="actions">
            <a class="btn btn-dark" href="?edit=<?= (int)$r['id'] ?>"><i class="fa-solid fa-pen-to-square"></i> تعديل</a>
            <a class="btn btn-dark" href="?delete=<?= (int)$r['id'] ?>&csrf=<?= $csrf ?>" onclick="return confirm('حذف الشريك نهائيًا؟')"><i class="fa-solid fa-trash"></i> حذف</a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?><tr><td colspan="7" style="text-align:center;color:#aaa">لا توجد سجلات</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>

  <?php if (isset($_GET['edit'])):
    $id = (int)$_GET['edit'];
    $row = db()->prepare("SELECT * FROM partners WHERE id=?");
    $row->execute([$id]);
    $row = $row->fetch(PDO::FETCH_ASSOC);
    if ($row):
  ?>
  <div class="card">
    <h3>تعديل شريك #<?= (int)$row['id'] ?></h3>
    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
      <div class="grid">
        <div>
          <label>اسم الشريك</label>
          <input name="name" value="<?= htmlspecialchars($row['name']) ?>" required>
        </div>
        <div>
          <label>رابط الموقع (اختياري)</label>
          <input name="url" value="<?= htmlspecialchars($row['url']) ?>">
        </div>
      </div>
      <div class="grid">
        <div>
          <label>الترتيب</label>
          <input type="number" name="sort" value="<?= (int)$row['sort'] ?>">
        </div>
        <div>
          <label>الحالة</label>
          <select name="status">
            <option value="1"<?= $row['status']?' selected':'' ?>>مفعل</option>
            <option value="0"<?= !$row['status']?' selected':'' ?>>معطل</option>
          </select>
        </div>
      </div>
      <div style="margin-top:8px">
        <label>شعار جديد (اتركه فارغًا للإبقاء على الحالي)</label>
        <input type="file" name="logo" accept=".png,.jpg,.jpeg,.webp,.svg">
      </div>
      <div style="margin-top:12px">
        <button class="btn btn-gold"><i class="fa-solid fa-save"></i> حفظ</button>
        <a class="btn btn-dark" href="partners.php">رجوع</a>
      </div>
    </form>
  </div>
  <?php endif; endif; ?>

</div>
</body>
</html>
<?php include "partials/footer.php"; ?>
