<?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);
$canSwitch  = 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 (!$canSwitch) {
    $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 = [];

$name         = trim((string)($_POST['name'] ?? (string)$client['name']));
$idNumber     = trim((string)($_POST['id_number'] ?? (string)($client['id_number'] ?? '')));
$phone        = trim((string)($_POST['phone'] ?? (string)($client['phone'] ?? '')));
$email        = trim((string)($_POST['email'] ?? (string)($client['email'] ?? '')));
$notes        = trim((string)($_POST['notes'] ?? (string)($client['notes'] ?? '')));
$reminderDate = trim((string)($_POST['reminder_date'] ?? (string)($client['reminder_date'] ?? '')));
$branchId     = $canSwitch
    ? (int)($_POST['branch_id'] ?? (int)$client['branch_id'])
    : $userBranch;

$currentDocument = (string)($client['document'] ?? '');
$removeDocument  = isset($_POST['remove_document']) && $_POST['remove_document'] === '1';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($name === '') {
        $errors[] = 'يرجى إدخال اسم العميل.';
    }

    if ($phone === '' && $email === '') {
        $errors[] = 'يرجى إدخال رقم الهاتف أو البريد الإلكتروني على الأقل.';
    }

    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'صيغة البريد الإلكتروني غير صحيحة.';
    }

    if ($branchId < 1 || $branchId > 4) {
        $branchId = (int)$client['branch_id'];
    }

    $documentName = $currentDocument;
    $newDocument = '';

    if ($removeDocument) {
        $documentName = null;
    }

    if (
        isset($_FILES['document']) &&
        is_array($_FILES['document']) &&
        (int)($_FILES['document']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE
    ) {
        $fileError = (int)($_FILES['document']['error'] ?? UPLOAD_ERR_NO_FILE);

        if ($fileError !== UPLOAD_ERR_OK) {
            $errors[] = 'حدث خطأ أثناء رفع الملف.';
        } else {
            $tmpPath  = (string)($_FILES['document']['tmp_name'] ?? '');
            $origName = (string)($_FILES['document']['name'] ?? '');
            $ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

            $allowed = ['pdf', 'jpg', 'jpeg', 'png', 'webp', 'doc', 'docx'];

            if (!in_array($ext, $allowed, true)) {
                $errors[] = 'نوع الملف غير مسموح. الأنواع المسموحة: PDF, JPG, PNG, WEBP, DOC, DOCX.';
            } else {
                $uploadDir = __DIR__ . '/../uploads/clients';
                if (!is_dir($uploadDir)) {
                    @mkdir($uploadDir, 0775, true);
                }

                if (!is_dir($uploadDir)) {
                    $errors[] = 'تعذر إنشاء مجلد رفع الملفات.';
                } else {
                    $newDocument = 'client_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                    $destPath = $uploadDir . '/' . $newDocument;

                    if (!@move_uploaded_file($tmpPath, $destPath)) {
                        $errors[] = 'تعذر حفظ الملف المرفوع.';
                        $newDocument = '';
                    } else {
                        $documentName = $newDocument;
                    }
                }
            }
        }
    }

    if (!$errors) {
        try {
            $st = $pdo->prepare("
                UPDATE clients
                SET
                    name = :name,
                    id_number = :id_number,
                    phone = :phone,
                    email = :email,
                    notes = :notes,
                    reminder_date = :reminder_date,
                    document = :document,
                    branch_id = :branch_id
                WHERE id = :id
            ");

            $st->execute([
                ':name'          => $name,
                ':id_number'     => $idNumber !== '' ? $idNumber : null,
                ':phone'         => $phone !== '' ? $phone : null,
                ':email'         => $email !== '' ? $email : null,
                ':notes'         => $notes !== '' ? $notes : null,
                ':reminder_date' => $reminderDate !== '' ? $reminderDate : null,
                ':document'      => $documentName,
                ':branch_id'     => $branchId,
                ':id'            => $clientId,
            ]);

            if ($removeDocument && $currentDocument !== '' && $currentDocument !== $newDocument) {
                $oldPath = __DIR__ . '/../uploads/clients/' . $currentDocument;
                if (is_file($oldPath)) {
                    @unlink($oldPath);
                }
            }

            if ($newDocument !== '' && $currentDocument !== '' && $currentDocument !== $newDocument) {
                $oldPath = __DIR__ . '/../uploads/clients/' . $currentDocument;
                if (is_file($oldPath)) {
                    @unlink($oldPath);
                }
            }

            header('Location: ' . u('clients/view.php') . '?id=' . (int)$clientId . '&updated=1');
            exit;
        } catch (Throwable $e) {
            $errors[] = 'تعذر تحديث بيانات العميل حاليًا.';
        }
    }
}

render_layout_start('تعديل العميل');
?>

<style>
.clients-edit-shell{
  width:100%;
  max-width:100%;
}

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

.clients-edit-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);
}

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

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

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

.clients-edit-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;
}

.clients-edit-top-btn.primary{
  border:1px solid rgba(0,106,122,.45);
  background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
}

.clients-edit-form-card{
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.04);
  border-radius:24px;
  padding:20px;
  box-shadow:0 14px 34px rgba(0,0,0,.16);
}

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

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

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

.clients-edit-grid{
  display:grid;
  grid-template-columns:repeat(2, minmax(0,1fr));
  gap:16px;
}

.clients-field{
  display:flex;
  flex-direction:column;
  gap:8px;
  min-width:0;
}

.clients-field.full{
  grid-column:1 / -1;
}

.clients-label{
  color:#fff;
  font-size:14px;
  font-weight:800;
}

.clients-input,
.clients-select,
.clients-textarea,
.clients-file{
  width:100%;
  min-width:0;
  border-radius:14px;
  border:1px solid rgba(255,255,255,.10);
  background:rgba(0,0,0,.18);
  color:#fff;
  font:inherit;
  outline:none;
}

.clients-input,
.clients-select,
.clients-file{
  height:50px;
  padding:0 14px;
}

.clients-textarea{
  min-height:130px;
  padding:12px 14px;
  resize:vertical;
}

.clients-input::placeholder,
.clients-textarea::placeholder{
  color:rgba(255,255,255,.45);
}

.clients-select option{
  background:#0b2633;
  color:#fff;
}

.clients-help{
  color:var(--layout-muted);
  font-size:12px;
  line-height:1.7;
}

.clients-current-file{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  flex-wrap:wrap;
  border:1px solid rgba(255,255,255,.08);
  background:rgba(255,255,255,.03);
  border-radius:16px;
  padding:14px;
}

.clients-current-file a{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:38px;
  padding:0 14px;
  border-radius:12px;
  text-decoration:none;
  font-size:13px;
  font-weight:800;
  color:#fff;
  background:#0b91b1;
}

.clients-check-row{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
  margin-top:10px;
  color:#fff;
  font-size:14px;
  font-weight:700;
}

.clients-actions{
  display:flex;
  align-items:center;
  gap:10px;
  flex-wrap:wrap;
  margin-top:20px;
}

.clients-submit-btn,
.clients-cancel-btn{
  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;
}

.clients-submit-btn{
  border:1px solid rgba(0,106,122,.45);
  background:linear-gradient(180deg, rgba(0,106,122,.35), rgba(0,66,79,.18));
  color:#fff;
}

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

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

  .clients-edit-grid{
    grid-template-columns:1fr;
  }

  .clients-edit-title{
    font-size:28px;
  }
}
</style>

<div class="clients-edit-shell">
  <div class="clients-edit-hero">
    <div class="clients-edit-hero-card">
      <h1 class="clients-edit-title">تعديل العميل</h1>
      <p class="clients-edit-sub">قم بتحديث بيانات العميل الحالية وتعديل الملف أو الملاحظات أو الفرع حسب الصلاحية المتاحة.</p>
    </div>

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

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

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

      <div class="clients-edit-grid">
        <div class="clients-field">
          <label class="clients-label" for="name">اسم العميل</label>
          <input class="clients-input" type="text" id="name" name="name" value="<?= h($name) ?>" placeholder="مثال: أحمد محمد" required>
        </div>

        <div class="clients-field">
          <label class="clients-label" for="id_number">رقم الهوية</label>
          <input class="clients-input" type="text" id="id_number" name="id_number" value="<?= h($idNumber) ?>" placeholder="مثال: 784-XXXXXXX-X">
        </div>

        <div class="clients-field">
          <label class="clients-label" for="phone">رقم الهاتف</label>
          <input class="clients-input" type="text" id="phone" name="phone" value="<?= h($phone) ?>" placeholder="05XXXXXXXX">
        </div>

        <div class="clients-field">
          <label class="clients-label" for="email">البريد الإلكتروني</label>
          <input class="clients-input" type="email" id="email" name="email" value="<?= h($email) ?>" placeholder="name@example.com">
        </div>

        <div class="clients-field">
          <label class="clients-label" for="branch_id">الفرع</label>
          <?php if ($canSwitch): ?>
            <select class="clients-select" id="branch_id" name="branch_id">
              <option value="1" <?= $branchId === 1 ? 'selected' : '' ?>>أبوظبي</option>
              <option value="2" <?= $branchId === 2 ? 'selected' : '' ?>>دبي</option>
              <option value="3" <?= $branchId === 3 ? 'selected' : '' ?>>الشارقة</option>
              <option value="4" <?= $branchId === 4 ? 'selected' : '' ?>>العين</option>
            </select>
          <?php else: ?>
            <input type="hidden" name="branch_id" value="<?= (int)$branchId ?>">
            <div class="clients-input" style="display:flex;align-items:center;"><?= h(branch_name_ar_simple($branchId)) ?></div>
          <?php endif; ?>
        </div>

        <div class="clients-field">
          <label class="clients-label" for="reminder_date">تاريخ التذكير</label>
          <input class="clients-input" type="date" id="reminder_date" name="reminder_date" value="<?= h($reminderDate) ?>">
        </div>

        <div class="clients-field full">
          <label class="clients-label">الملف الحالي</label>

          <?php if ($currentDocument !== ''): ?>
            <div class="clients-current-file">
              <div><?= h($currentDocument) ?></div>
              <a href="<?= h(u('uploads/clients/' . rawurlencode($currentDocument))) ?>" target="_blank" rel="noopener">فتح الملف</a>
            </div>

            <label class="clients-check-row">
              <input type="checkbox" name="remove_document" value="1">
              حذف الملف الحالي
            </label>
          <?php else: ?>
            <div class="clients-help">لا يوجد ملف مرفق حاليًا.</div>
          <?php endif; ?>
        </div>

        <div class="clients-field full">
          <label class="clients-label" for="document">رفع ملف جديد</label>
          <input class="clients-file" type="file" id="document" name="document" accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx">
          <div class="clients-help">يمكن رفع ملف جديد لاستبدال الملف الحالي أو إضافته إن لم يوجد.</div>
        </div>

        <div class="clients-field full">
          <label class="clients-label" for="notes">ملاحظات</label>
          <textarea class="clients-textarea" id="notes" name="notes" placeholder="أي ملاحظات إضافية عن العميل"><?= h($notes) ?></textarea>
        </div>
      </div>

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

<?php
render_layout_end();
?>