<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header('Location: ../index.html?e=1');
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('branch_name_ar_simple')) {
    function branch_name_ar_simple(int $branchId): string
    {
        return match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'الشارقة',
            4 => 'العين',
            default => 'غير محدد',
        };
    }
}

$role       = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$userBranch = (int)($_SESSION['branch_id'] ?? 1);
$canManageAll = in_array($role, ['OWNER', 'ADMIN'], true);

$clientId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($clientId <= 0) {
    http_response_code(404);
    exit('العميل غير موجود.');
}

$sql = "
    SELECT
        id,
        name,
        id_number,
        phone,
        email,
        notes,
        reminder_date,
        created_at,
        document,
        branch_id
    FROM clients
    WHERE id = :id
";

$params = [':id' => $clientId];

if (!$canManageAll) {
    $sql .= " AND branch_id = :branch_id ";
    $params[':branch_id'] = $userBranch;
}

$sql .= " LIMIT 1 ";

$st = $pdo->prepare($sql);
$st->execute($params);
$client = $st->fetch();

if (!$client) {
    http_response_code(404);
    exit('تعذر العثور على العميل.');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirm = (string)($_POST['confirm_delete'] ?? '');

    if ($confirm !== 'yes') {
        $errors[] = 'يرجى تأكيد الحذف أولاً.';
    }

    if (!$errors) {
        try {
            $pdo->beginTransaction();

            $deleteSt = $pdo->prepare("DELETE FROM clients WHERE id = :id LIMIT 1");
            $deleteSt->execute([':id' => $clientId]);

            if ($pdo->inTransaction()) {
                $pdo->commit();
            }

            $document = trim((string)($client['document'] ?? ''));
            if ($document !== '') {
                $filePath = __DIR__ . '/../uploads/clients/' . $document;
                if (is_file($filePath)) {
                    @unlink($filePath);
                }
            }

            header('Location: ' . u('clients/index.php?deleted=1'));
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = 'تعذر حذف العميل حاليًا.';
        }
    }
}

render_layout_start('حذف العميل');
?>

<style>
.client-delete-shell{
  width:100%;
  max-width:100%;
}

.client-delete-hero{
  display:grid;
  grid-template-columns:minmax(0,1fr) auto;
  gap:16px;
  align-items:start;
  margin-bottom:18px;
}

.client-delete-hero-card{
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(135deg, rgba(255,255,255,.05), rgba(255,255,255,.03));
  border-radius:22px;
  padding:22px;
  box-shadow:0 14px 34px rgba(0,0,0,.18);
}

.client-delete-title{
  margin:0 0 6px;
  font-size:34px;
  font-weight:900;
  line-height:1.1;
  color:#fff;
}

.client-delete-sub{
  margin:0;
  color:var(--layout-muted);
  font-size:15px;
  line-height:1.8;
}

.client-delete-top-actions{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
}

.client-delete-top-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:50px;
  padding:0 18px;
  border-radius:15px;
  text-decoration:none;
  font-weight:800;
  white-space:nowrap;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.05);
  color:#fff;
}

.client-delete-card{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.04);
  border-radius:24px;
  overflow:hidden;
  box-shadow:0 14px 34px rgba(0,0,0,.16);
}

.client-delete-card-head{
  padding:18px 20px;
  border-bottom:1px solid rgba(255,255,255,.08);
  background:linear-gradient(180deg, rgba(255,90,90,.18), rgba(255,255,255,.02));
}

.client-delete-card-title{
  margin:0;
  color:#fff;
  font-size:18px;
  font-weight:900;
}

.client-delete-card-body{
  padding:20px;
}

.client-delete-alert{
  border-radius:16px;
  padding:14px 16px;
  margin-bottom:14px;
  font-weight:700;
}

.client-delete-alert.error{
  background:rgba(255,107,107,.12);
  border:1px solid rgba(255,107,107,.28);
  color:#fff;
}

.client-delete-errors{
  margin:0;
  padding-right:18px;
}

.client-delete-warning{
  border:1px solid rgba(255,200,80,.22);
  background:rgba(255,200,80,.08);
  border-radius:18px;
  padding:16px;
  color:#fff;
  line-height:1.9;
  margin-bottom:16px;
}

.client-delete-grid{
  display:grid;
  grid-template-columns:repeat(2, minmax(0,1fr));
  gap:14px;
  margin-bottom:16px;
}

.client-delete-field{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.03);
  border-radius:18px;
  padding:14px;
  min-width:0;
}

.client-delete-label{
  color:var(--layout-muted);
  font-size:13px;
  margin-bottom:8px;
}

.client-delete-value{
  color:#fff;
  font-size:15px;
  font-weight:800;
  line-height:1.8;
  word-break:break-word;
}

.client-delete-check{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
  color:#fff;
  font-size:14px;
  font-weight:700;
  margin:18px 0;
}

.client-delete-actions{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
}

.client-delete-btn,
.client-delete-cancel{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:48px;
  padding:0 18px;
  border-radius:14px;
  font:inherit;
  font-weight:800;
  text-decoration:none;
  cursor:pointer;
  white-space:nowrap;
}

.client-delete-btn{
  border:1px solid rgba(255,107,107,.32);
  background:linear-gradient(180deg, rgba(255,107,107,.28), rgba(160,30,30,.24));
  color:#fff;
}

.client-delete-cancel{
  border:1px solid rgba(255,255,255,.10);
  background:rgba(255,255,255,.04);
  color:#fff;
}

.client-delete-branch{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:82px;
  padding:7px 14px;
  border-radius:999px;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.10);
  color:#fff;
  font-size:12px;
  font-weight:900;
}

@media (max-width: 900px){
  .client-delete-hero{
    grid-template-columns:1fr;
  }

  .client-delete-grid{
    grid-template-columns:1fr;
  }

  .client-delete-title{
    font-size:28px;
  }
}
</style>

<div class="client-delete-shell">
  <div class="client-delete-hero">
    <div class="client-delete-hero-card">
      <h1 class="client-delete-title">حذف العميل</h1>
      <p class="client-delete-sub">راجع بيانات العميل جيدًا قبل الحذف النهائي من النظام.</p>
    </div>

    <div class="client-delete-top-actions">
      <a class="client-delete-top-btn" href="<?= h(u('clients/index.php')) ?>">العودة</a>
      <a class="client-delete-top-btn" href="<?= h(u('clients/view.php?id=' . $clientId)) ?>">عرض العميل</a>
    </div>
  </div>

  <div class="client-delete-card">
    <div class="client-delete-card-head">
      <h2 class="client-delete-card-title">تأكيد الحذف</h2>
    </div>

    <div class="client-delete-card-body">
      <?php if ($errors): ?>
        <div class="client-delete-alert error">
          <ul class="client-delete-errors">
            <?php foreach ($errors as $err): ?>
              <li><?= h($err) ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php endif; ?>

      <div class="client-delete-warning">
        هذا الإجراء سيؤدي إلى حذف العميل من النظام. تأكد أنك تريد المتابعة قبل الضغط على زر الحذف.
      </div>

      <div class="client-delete-grid">
        <div class="client-delete-field">
          <div class="client-delete-label">اسم العميل</div>
          <div class="client-delete-value"><?= h($client['name'] ?? '-') ?></div>
        </div>

        <div class="client-delete-field">
          <div class="client-delete-label">رقم العميل</div>
          <div class="client-delete-value">#<?= (int)($client['id'] ?? 0) ?></div>
        </div>

        <div class="client-delete-field">
          <div class="client-delete-label">رقم الهوية</div>
          <div class="client-delete-value"><?= h($client['id_number'] ?? '-') ?></div>
        </div>

        <div class="client-delete-field">
          <div class="client-delete-label">الهاتف</div>
          <div class="client-delete-value"><?= h($client['phone'] ?? '-') ?></div>
        </div>

        <div class="client-delete-field">
          <div class="client-delete-label">البريد الإلكتروني</div>
          <div class="client-delete-value"><?= h($client['email'] ?? '-') ?></div>
        </div>

        <div class="client-delete-field">
          <div class="client-delete-label">الفرع</div>
          <div class="client-delete-value">
            <span class="client-delete-branch"><?= h(branch_name_ar_simple((int)($client['branch_id'] ?? 0))) ?></span>
          </div>
        </div>
      </div>

      <form method="post" novalidate>
        <input type="hidden" name="id" value="<?= (int)$clientId ?>">

        <label class="client-delete-check">
          <input type="checkbox" name="confirm_delete" value="yes">
          أؤكد أنني أريد حذف هذا العميل نهائيًا
        </label>

        <div class="client-delete-actions">
          <button class="client-delete-btn" type="submit">حذف العميل</button>
          <a class="client-delete-cancel" href="<?= h(u('clients/view.php?id=' . $clientId)) ?>">إلغاء</a>
        </div>
      </form>
    </div>
  </div>
</div>

<?php
render_layout_end();
?>