<?php
declare(strict_types=1);

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

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

if (empty($_SESSION['user_id'])) {
    header("Location: ../index.html");
    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($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('table_columns')) {
    function table_columns(PDO $pdo, string $table): array
    {
        $st = $pdo->prepare("
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
        ");
        $st->execute([$table]);
        return $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
    }
}

if (!function_exists('has_col')) {
    function has_col(array $cols, string $name): bool
    {
        return in_array($name, $cols, true);
    }
}

if (!function_exists('strip_html_to_text')) {
    function strip_html_to_text(string $html): string
    {
        $text = preg_replace('/<br\s*\/?>/i', "\n", $html);
        $text = preg_replace('/<\/p>/i', "\n\n", (string)$text);
        $text = preg_replace('/<\/div>/i', "\n", (string)$text);
        $text = strip_tags((string)$text);
        $text = html_entity_decode((string)$text, ENT_QUOTES, 'UTF-8');
        $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
        return trim((string)$text);
    }
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    exit('رقم العقد غير صحيح');
}

$contractCols = table_columns($pdo, 'contracts');

/* ===== تحديد أعمدة المحتوى ===== */
$contractHtmlCol = null;
foreach (['contract_html', 'content_html', 'html_content', 'template_html', 'body_html'] as $col) {
    if (has_col($contractCols, $col)) {
        $contractHtmlCol = $col;
        break;
    }
}

$contractTextCol = null;
foreach (['contract_content', 'content', 'body', 'description', 'details', 'contract_text', 'text_content'] as $col) {
    if (has_col($contractCols, $col)) {
        $contractTextCol = $col;
        break;
    }
}

$titleExpr = has_col($contractCols, 'contract_name')
    ? 'c.contract_name'
    : (has_col($contractCols, 'title') ? 'c.title' : "''");

$startDateExpr = has_col($contractCols, 'start_date')
    ? 'c.start_date'
    : "NULL";

$endDateExpr = has_col($contractCols, 'end_date')
    ? 'c.end_date'
    : "NULL";

$contractHtmlExpr = $contractHtmlCol ? "c.`{$contractHtmlCol}`" : "NULL";
$contractTextExpr = $contractTextCol ? "c.`{$contractTextCol}`" : "NULL";

$stmt = $pdo->prepare("
    SELECT
        c.*,
        {$titleExpr} AS contract_title_value,
        {$startDateExpr} AS contract_start_date_value,
        {$endDateExpr} AS contract_end_date_value,
        {$contractHtmlExpr} AS contract_html_value,
        {$contractTextExpr} AS contract_text_value
    FROM contracts c
    WHERE c.id = ?
    LIMIT 1
");
$stmt->execute([$id]);
$contract = $stmt->fetch();

if (!$contract) {
    exit('العقد غير موجود');
}

$message = [];

/* العملاء */
$clients = $pdo->query("
    SELECT id, name
    FROM clients
    WHERE name IS NOT NULL AND name <> ''
    ORDER BY name ASC
")->fetchAll();

/* المحامين */
$employeeCols = table_columns($pdo, 'employees');
$employeeNameCol = in_array('full_name', $employeeCols, true) ? 'full_name' : 'name';
$hasEmployeeType = in_array('employee_type', $employeeCols, true);

if ($hasEmployeeType) {
    $stmt = $pdo->prepare("
        SELECT MIN(id) AS id, `{$employeeNameCol}` AS full_name
        FROM employees
        WHERE employee_type = 'lawyer'
          AND `{$employeeNameCol}` IS NOT NULL
          AND `{$employeeNameCol}` <> ''
        GROUP BY `{$employeeNameCol}`
        ORDER BY `{$employeeNameCol}` ASC
    ");
    $stmt->execute();
    $lawyers = $stmt->fetchAll();
} else {
    $lawyers = $pdo->query("
        SELECT MIN(id) AS id, `{$employeeNameCol}` AS full_name
        FROM employees
        WHERE `{$employeeNameCol}` IS NOT NULL
          AND `{$employeeNameCol}` <> ''
        GROUP BY `{$employeeNameCol}`
        ORDER BY `{$employeeNameCol}` ASC
    ")->fetchAll();
}

/* أنواع العقود */
$typeCols = table_columns($pdo, 'contract_types');
$typeNameCol = in_array('contract_name', $typeCols, true) ? 'contract_name' : 'name';

$types = $pdo->query("
    SELECT id, `{$typeNameCol}` AS contract_type_name
    FROM contract_types
    ORDER BY `{$typeNameCol}` ASC
")->fetchAll();

/* القيم الافتراضية */
$contractHtmlInput = trim((string)(
    $_POST['contract_html']
    ?? $contract['contract_html_value']
    ?? $contract['contract_text_value']
    ?? ''
));

/* التحديث */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title            = trim((string)($_POST['title'] ?? ''));
    $client_id        = (int)($_POST['client_id'] ?? 0);
    $lawyer_id        = (int)($_POST['lawyer_id'] ?? 0);
    $contract_type_id = (int)($_POST['contract_type_id'] ?? 0);
    $status           = trim((string)($_POST['status'] ?? ''));
    $start_date       = trim((string)($_POST['start_date'] ?? ''));
    $end_date         = trim((string)($_POST['end_date'] ?? ''));
    $contractHtmlInput = trim((string)($_POST['contract_html'] ?? ''));

    if ($title === '') {
        $message[] = 'يرجى إدخال عنوان العقد.';
    }
    if ($client_id <= 0) {
        $message[] = 'يرجى اختيار العميل.';
    }
    if ($lawyer_id <= 0) {
        $message[] = 'يرجى اختيار المحامي.';
    }
    if ($start_date !== '' && $end_date !== '' && $end_date < $start_date) {
        $message[] = 'تاريخ الانتهاء يجب أن يكون بعد أو مساويًا لتاريخ البداية.';
    }

    if (!$message) {
        $updateParts = [];
        $params = [];

        if (has_col($contractCols, 'contract_name')) {
            $updateParts[] = 'contract_name = ?';
            $params[] = $title;
        }

        if (has_col($contractCols, 'title')) {
            $updateParts[] = 'title = ?';
            $params[] = $title;
        }

        if (has_col($contractCols, 'client_id')) {
            $updateParts[] = 'client_id = ?';
            $params[] = $client_id;
        }

        if (has_col($contractCols, 'lawyer_id')) {
            $updateParts[] = 'lawyer_id = ?';
            $params[] = $lawyer_id;
        }

        if (has_col($contractCols, 'contract_type_id')) {
            $updateParts[] = 'contract_type_id = ?';
            $params[] = $contract_type_id > 0 ? $contract_type_id : null;
        }

        if (has_col($contractCols, 'status')) {
            $updateParts[] = 'status = ?';
            $params[] = $status;
        }

        if (has_col($contractCols, 'start_date')) {
            $updateParts[] = 'start_date = ?';
            $params[] = $start_date !== '' ? $start_date : null;
        }

        if (has_col($contractCols, 'end_date')) {
            $updateParts[] = 'end_date = ?';
            $params[] = $end_date !== '' ? $end_date : null;
        }

        if ($contractHtmlCol !== null) {
            $updateParts[] = "`{$contractHtmlCol}` = ?";
            $params[] = $contractHtmlInput !== '' ? $contractHtmlInput : null;
        }

        if ($contractTextCol !== null) {
            $updateParts[] = "`{$contractTextCol}` = ?";
            $params[] = $contractHtmlInput !== '' ? strip_html_to_text($contractHtmlInput) : null;
        }

        if (has_col($contractCols, 'updated_at')) {
            $updateParts[] = 'updated_at = NOW()';
        }

        if (!$updateParts) {
            $message[] = 'تعذر تحديد أعمدة قابلة للتحديث في جدول العقود.';
        } else {
            $params[] = $id;

            $stmt = $pdo->prepare("
                UPDATE contracts
                SET " . implode(",\n                ", $updateParts) . "
                WHERE id = ?
            ");
            $stmt->execute($params);

            header("Location: view_contract.php?id=" . $id . "&updated=1");
            exit;
        }
    }

    $contract['contract_title_value'] = $title;
    $contract['client_id'] = $client_id;
    $contract['lawyer_id'] = $lawyer_id;
    $contract['contract_type_id'] = $contract_type_id;
    $contract['status'] = $status;
    $contract['contract_start_date_value'] = $start_date;
    $contract['contract_end_date_value'] = $end_date;
}

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

<style>
.contract-page{max-width:1400px;margin:auto;padding:30px 30px 40px}
.contract-head{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;flex-wrap:wrap;margin-bottom:30px}
.contract-title h2{margin:0;font-size:26px}
.contract-title .muted{font-size:13px;color:#8a9aa3;margin-top:6px}
.contract-grid{display:grid;grid-template-columns:1fr 1fr;gap:26px;margin-top:10px}
.contract-full{grid-column:1 / -1}
.contract-grid label{display:block;font-size:14px;margin-bottom:6px}
.field-help{font-size:12px;color:#9aa7ad;margin-bottom:8px}
.contract-grid input,.contract-grid select,.contract-grid textarea{width:100%;padding:12px 16px;border-radius:12px}
.contract-grid input,.contract-grid select{height:48px}
.contract-grid textarea{min-height:340px;resize:vertical;line-height:2}
.contract-actions{margin-top:32px;display:flex;gap:12px;flex-wrap:wrap}
.contract-alert{margin-bottom:18px}
.contract-select,select.input,input.input,textarea.input{background:#071a23 !important;color:#ffffff !important;border:1px solid rgba(255,255,255,.12) !important}
.contract-select option,select.input option{background:#0b2230;color:#ffffff}
.contract-select:focus,select.input:focus,input.input:focus,textarea.input:focus{outline:none;border-color:#0ea5b7 !important;box-shadow:0 0 0 3px rgba(14,165,183,.18)}
.editor-note{font-size:12px;color:#9aa7ad;margin-top:8px;line-height:1.8}
@media (max-width:900px){.contract-grid{grid-template-columns:1fr}}
</style>

<div class="card contract-page">
  <div class="cardHead contract-head">
    <div class="contract-title">
      <h2>تعديل العقد</h2>
      <div class="muted">يمكنك تحديث بيانات العقد ونصه ثم حفظ التعديلات.</div>
    </div>
    <a href="index.php" class="btn ghost">← رجوع</a>
  </div>

  <?php if ($message): ?>
    <div class="msg err contract-alert"><?= h(implode(' ', $message)) ?></div>
  <?php endif; ?>

  <form method="post">
    <div class="contract-grid">
      <div class="contract-full">
        <label>عنوان العقد</label>
        <div class="field-help">أدخل الاسم الرسمي للعقد كما سيظهر داخل النظام.</div>
        <input class="input" type="text" name="title" value="<?= h($contract['contract_title_value'] ?? '') ?>">
      </div>

      <div>
        <label>العميل</label>
        <div class="field-help">اختر العميل المرتبط بهذا العقد.</div>
        <select class="input contract-select" name="client_id">
          <option value="">اختر العميل</option>
          <?php foreach ($clients as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= (string)($contract['client_id'] ?? '') === (string)$c['id'] ? 'selected' : '' ?>>
              <?= h($c['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>المحامي</label>
        <div class="field-help">اختر المحامي المسؤول عن هذا العقد.</div>
        <select class="input contract-select" name="lawyer_id">
          <option value="">اختر المحامي</option>
          <?php foreach ($lawyers as $l): ?>
            <option value="<?= (int)$l['id'] ?>" <?= (string)($contract['lawyer_id'] ?? '') === (string)$l['id'] ? 'selected' : '' ?>>
              <?= h($l['full_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>نوع العقد</label>
        <div class="field-help">اختر تصنيف العقد المناسب.</div>
        <select class="input contract-select" name="contract_type_id">
          <option value="">اختر نوع العقد</option>
          <?php foreach ($types as $t): ?>
            <option value="<?= (int)$t['id'] ?>" <?= (string)($contract['contract_type_id'] ?? '') === (string)$t['id'] ? 'selected' : '' ?>>
              <?= h($t['contract_type_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>الحالة</label>
        <div class="field-help">اختر الحالة الحالية لهذا العقد.</div>
        <select class="input contract-select" name="status">
          <option value="draft" <?= (string)($contract['status'] ?? '') === 'draft' ? 'selected' : '' ?>>مسودة</option>
          <option value="pending_review" <?= (string)($contract['status'] ?? '') === 'pending_review' ? 'selected' : '' ?>>قيد المراجعة</option>
          <option value="active" <?= (string)($contract['status'] ?? '') === 'active' ? 'selected' : '' ?>>ساري</option>
          <option value="signed" <?= (string)($contract['status'] ?? '') === 'signed' ? 'selected' : '' ?>>موقع</option>
          <option value="sent_for_sign" <?= (string)($contract['status'] ?? '') === 'sent_for_sign' ? 'selected' : '' ?>>مرسل للتوقيع</option>
          <option value="expired" <?= (string)($contract['status'] ?? '') === 'expired' ? 'selected' : '' ?>>منتهي</option>
          <option value="cancelled" <?= (string)($contract['status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>ملغي</option>
        </select>
      </div>

      <div>
        <label>تاريخ البداية</label>
        <div class="field-help">أدخل تاريخ بدء العقد.</div>
        <input type="date" class="input" name="start_date" value="<?= h($contract['contract_start_date_value'] ?? '') ?>">
      </div>

      <div>
        <label>تاريخ الانتهاء</label>
        <div class="field-help">أدخل تاريخ انتهاء العقد.</div>
        <input type="date" class="input" name="end_date" value="<?= h($contract['contract_end_date_value'] ?? '') ?>">
      </div>

      <div class="contract-full">
        <label>نص العقد</label>
        <div class="field-help">يمكنك تعديل نص العقد هنا ليظهر لاحقًا في صفحة التوقيع الإلكتروني.</div>
        <textarea class="input" name="contract_html" placeholder="اكتب أو عدّل نص العقد هنا..."><?= h($contractHtmlInput) ?></textarea>
        <div class="editor-note">
          سيتم حفظ النص في عمود HTML أو النص المتاح في جدول العقود إذا كان موجودًا.
        </div>
      </div>
    </div>

    <div class="contract-actions">
      <button class="btn" type="submit">حفظ التعديل</button>
      <a href="index.php" class="btn ghost">رجوع</a>
    </div>
  </form>
</div>

<?php render_layout_end(); ?>