<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';

$db = $conn instanceof mysqli ? $conn : (($GLOBALS['mysqli'] ?? null) instanceof mysqli ? $GLOBALS['mysqli'] : null);
if (!$db) {
    die('Database connection not found');
}

$db->query("CREATE TABLE IF NOT EXISTS customer_deletion_requests (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NOT NULL,
    reason TEXT NULL,
    status VARCHAR(40) NOT NULL DEFAULT 'pending',
    requested_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    processed_at DATETIME NULL,
    admin_notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_customer_deletion_customer (customer_id),
    KEY idx_customer_deletion_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

function dr_h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

$flash = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $status = trim((string)($_POST['status'] ?? ''));
    $notes = trim((string)($_POST['admin_notes'] ?? ''));
    if ($id > 0 && in_array($status, ['pending', 'processing', 'completed', 'rejected'], true)) {
        $stmt = $db->prepare("UPDATE customer_deletion_requests SET status = ?, admin_notes = ?, processed_at = IF(? IN ('completed','rejected'), NOW(), processed_at), updated_at = NOW() WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param('sssi', $status, $notes, $status, $id);
            $stmt->execute();
            $stmt->close();
            $flash = 'تم تحديث الطلب.';
        }
    }
}

$sql = "SELECT r.*, c.full_name, c.phone, c.email, c.status AS customer_status
        FROM customer_deletion_requests r
        LEFT JOIN customers c ON c.id = r.customer_id
        ORDER BY r.id DESC
        LIMIT 200";
$result = $db->query($sql);
$rows = [];
if ($result) {
    while ($row = $result->fetch_assoc()) $rows[] = $row;
}

$page_title = 'طلبات حذف الحساب';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<div class="nay-dashboard-page">
  <div class="nay-dashboard-main">
    <div class="nay-dashboard-hero">
      <div>
        <h1>طلبات حذف الحساب</h1>
        <p>طلبات الحذف المرسلة من تطبيق الزبون. راجع الطلبات والرصيد والطلبات السابقة قبل إتمام الإجراء النهائي.</p>
      </div>
      <div class="nay-actions">
        <a class="nay-btn" href="index.php"><i class="fa-solid fa-users"></i> الزبائن</a>
        <a class="nay-btn primary" href="list.php"><i class="fa-solid fa-list"></i> قائمة الزبائن</a>
      </div>
    </div>

    <?php if ($flash): ?><div class="nay-card" style="border-color:#bbf7d0;background:#f0fdf4;color:#166534;margin-bottom:14px"><?= dr_h($flash) ?></div><?php endif; ?>

    <div class="nay-card">
      <?php if (!$rows): ?>
        <div class="nay-empty">ماكو طلبات حذف حساب حالياً.</div>
      <?php else: ?>
        <div class="nay-table-wrap">
          <table class="nay-table">
            <thead>
              <tr>
                <th>#</th>
                <th>الزبون</th>
                <th>الهاتف</th>
                <th>السبب</th>
                <th>الحالة</th>
                <th>التاريخ</th>
                <th>إجراء</th>
              </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $row): ?>
              <tr>
                <td><?= (int)$row['id'] ?></td>
                <td><?= dr_h($row['full_name'] ?: ('عميل #' . $row['customer_id'])) ?></td>
                <td><?= dr_h($row['phone'] ?? '') ?></td>
                <td style="max-width:280px;white-space:normal"><?= nl2br(dr_h($row['reason'] ?? '')) ?></td>
                <td><span class="badge bg-secondary"><?= dr_h($row['status'] ?? 'pending') ?></span></td>
                <td><?= dr_h($row['requested_at'] ?? '') ?></td>
                <td>
                  <form method="post" style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                    <select name="status" style="min-width:130px">
                      <?php foreach (['pending'=>'قيد المراجعة','processing'=>'قيد التنفيذ','completed'=>'تم الحذف','rejected'=>'مرفوض'] as $value=>$label): ?>
                        <option value="<?= dr_h($value) ?>" <?= ($row['status'] ?? '') === $value ? 'selected' : '' ?>><?= dr_h($label) ?></option>
                      <?php endforeach; ?>
                    </select>
                    <input type="text" name="admin_notes" value="<?= dr_h($row['admin_notes'] ?? '') ?>" placeholder="ملاحظة الإدارة" style="min-width:180px">
                    <button class="nay-btn primary" type="submit">حفظ</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
