<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../../db.php';
require_once __DIR__ . '/../../inc/layout.php';
require_once __DIR__ . '/../../inc/otp_helper.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($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

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

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

if (!function_exists('first_existing_column')) {
    function first_existing_column(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $col) {
            if (in_array($col, $columns, true)) {
                return $col;
            }
        }
        return null;
    }
}

if (!function_exists('generate_short_code')) {
    function generate_short_code(int $length = 6): string
    {
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $max   = strlen($chars) - 1;
        $code  = '';

        for ($i = 0; $i < $length; $i++) {
            $code .= $chars[random_int(0, $max)];
        }

        return $code;
    }
}

if (!function_exists('create_unique_short_code')) {
    function create_unique_short_code(PDO $pdo, int $length = 6): string
    {
        do {
            $code = generate_short_code($length);

            $st = $pdo->prepare("
                SELECT id
                FROM contract_sign_requests
                WHERE short_code = ?
                LIMIT 1
            ");
            $st->execute([$code]);
            $exists = $st->fetchColumn();
        } while ($exists);

        return $code;
    }
}

$userId = (int)($_SESSION['user_id'] ?? 0);

$contractId = (int)($_GET['contract_id'] ?? $_POST['contract_id'] ?? 0);
if ($contractId <= 0) {
    exit('العقد غير موجود');
}

$contractsCols    = table_columns($pdo, 'contracts');
$signReqCols      = table_columns($pdo, 'contract_sign_requests');
$contractLogsCols = table_columns($pdo, 'contract_logs');

$hasShortCode = has_col($signReqCols, 'short_code');
if (!$hasShortCode) {
    exit('يرجى أولاً إضافة عمود short_code إلى جدول contract_sign_requests.');
}

/* ===== تحديد أسماء أعمدة العقود بشكل مرن ===== */
$contractTitleCol = first_existing_column($contractsCols, [
    'title',
    'contract_name',
    'name',
    'subject'
]);

$contractNoCol = first_existing_column($contractsCols, [
    'contract_no',
    'transaction_id',
    'contract_number',
    'reference_no'
]);

$titleExpr = $contractTitleCol ? "c.`{$contractTitleCol}`" : "''";
$numberExpr = $contractNoCol ? "c.`{$contractNoCol}`" : "CAST(c.id AS CHAR)";

/* ===== جلب بيانات العقد والعميل ===== */
$st = $pdo->prepare("
    SELECT
        c.*,
        {$titleExpr}  AS contract_title_display,
        {$numberExpr} AS contract_no_display,
        cl.name  AS client_name,
        cl.email AS client_email,
        cl.phone AS client_phone
    FROM contracts c
    LEFT JOIN clients cl ON cl.id = c.client_id
    WHERE c.id = ?
    LIMIT 1
");
$st->execute([$contractId]);
$contract = $st->fetch();

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

$errors      = [];
$link        = '';
$shortCode   = '';
$messageOk   = '';

/* ===== القيم الافتراضية ===== */
$signerName  = trim((string)($_POST['signer_name'] ?? ($contract['client_name'] ?? '')));
$signerEmail = trim((string)($_POST['signer_email'] ?? ($contract['client_email'] ?? '')));
$signerPhone = trim((string)($_POST['signer_phone'] ?? ($contract['client_phone'] ?? '')));

$displayTitle = trim((string)($contract['contract_title_display'] ?? ''));
$displayNo    = trim((string)($contract['contract_no_display'] ?? ''));

/* ===== عند الإرسال ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($signerName === '') {
        $errors[] = 'يرجى كتابة اسم الموقّع.';
    }

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

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

    if (!$errors) {
        try {
            $token     = bin2hex(random_bytes(32));
            $shortCode = create_unique_short_code($pdo, 6);
            $ip        = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));

            $insertCols = [];
            $insertVals = [];
            $params     = [];

            $requiredMap = [
                'contract_id'   => $contractId,
                'signer_name'   => $signerName,
                'signer_email'  => $signerEmail !== '' ? $signerEmail : null,
                'signer_phone'  => $signerPhone !== '' ? $signerPhone : null,
                'sign_token'    => $token,
                'short_code'    => $shortCode,
                'status'        => 'pending',
                'ip_address'    => $ip,
            ];

            foreach ($requiredMap as $col => $val) {
                if (has_col($signReqCols, $col)) {
                    $insertCols[] = $col;
                    $insertVals[] = '?';
                    $params[]     = $val;
                }
            }

            if (has_col($signReqCols, 'sent_at')) {
                $insertCols[] = 'sent_at';
                $insertVals[] = 'NOW()';
            }

            if (has_col($signReqCols, 'created_at')) {
                $insertCols[] = 'created_at';
                $insertVals[] = 'NOW()';
            }

            if (!$insertCols) {
                throw new RuntimeException('تعذر تحديد أعمدة الحفظ في جدول contract_sign_requests.');
            }

            $pdo->beginTransaction();

            $ins = $pdo->prepare("
                INSERT INTO contract_sign_requests
                (" . implode(', ', $insertCols) . ")
                VALUES
                (" . implode(', ', $insertVals) . ")
            ");
            $ins->execute($params);

            /* ===== تحديث حالة العقد إن أمكن ===== */
            $updateParts  = [];
            $updateParams = [];

            if (has_col($contractsCols, 'status')) {
                $updateParts[] = "status = ?";
                $updateParams[] = 'sent_for_sign';
            }

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

            if ($updateParts) {
                $updateParams[] = $contractId;
                $up = $pdo->prepare("
                    UPDATE contracts
                    SET " . implode(', ', $updateParts) . "
                    WHERE id = ?
                ");
                $up->execute($updateParams);
            }

            /* ===== تسجيل اللوج إن أمكن ===== */
            if (
                has_col($contractLogsCols, 'contract_id') &&
                has_col($contractLogsCols, 'action')
            ) {
                $logCols   = ['contract_id', 'action'];
                $logVals   = ['?', '?'];
                $logParams = [$contractId, 'sent_for_sign'];

                if (has_col($contractLogsCols, 'notes')) {
                    $notes = 'تم إنشاء طلب توقيع للموقّع: ' . $signerName . ' | الكود المختصر: ' . $shortCode;

                    if ($signerEmail !== '') {
                        $notes .= ' | البريد: ' . mask_email($signerEmail);
                    }

                    if ($signerPhone !== '') {
                        $notes .= ' | الهاتف: ' . mask_phone($signerPhone);
                    }

                    $logCols[]   = 'notes';
                    $logVals[]   = '?';
                    $logParams[] = $notes;
                }

                if (has_col($contractLogsCols, 'action_by')) {
                    $logCols[]   = 'action_by';
                    $logVals[]   = '?';
                    $logParams[] = $userId > 0 ? $userId : null;
                }

                if (has_col($contractLogsCols, 'created_at')) {
                    $logCols[] = 'created_at';
                    $logVals[] = 'NOW()';
                }

                $log = $pdo->prepare("
                    INSERT INTO contract_logs
                    (" . implode(', ', $logCols) . ")
                    VALUES
                    (" . implode(', ', $logVals) . ")
                ");
                $log->execute($logParams);
            }

            $pdo->commit();

            $isHttps = (
                (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                || ((string)($_SERVER['SERVER_PORT'] ?? '') === '443')
            );

            $scheme = $isHttps ? 'https' : 'http';
            $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
            $currentDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');

            $link = $scheme . '://' . $host . $currentDir . '/signing.php?c=' . urlencode($shortCode);
            $messageOk = 'تم إنشاء رابط التوقيع المختصر بنجاح.';

        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = 'حدث خطأ أثناء إنشاء رابط التوقيع: ' . $e->getMessage();
        }
    }
}

render_layout_start('إرسال للتوقيع');
?>

<style>
:root{
  --d:#006a7a;
  --t:#006a7a;
  --line:#dce8eb;
  --shadow:0 18px 42px rgba(0,66,79,.08);
  --highlight:#d4af37;
  --text:#12343b;
  --muted:#5f7480;
  --bg:#f7fbfc;
}

.ss-wrap{
  direction:rtl;
  font-family:'Tajawal',sans-serif;
  padding:24px;
  max-width:980px;
  margin:0 auto;
}

.card{
  background:#fff;
  border:1px solid var(--line);
  border-radius:24px;
  box-shadow:var(--shadow);
  overflow:hidden;
}

.head{
  padding:18px 20px;
  border-bottom:1px solid #e8eff2;
  background:linear-gradient(180deg,#ffffff 0%, #fbfeff 100%);
}

.body{
  padding:22px;
}

.top-note{
  margin-top:0;
  margin-bottom:18px;
  line-height:1.9;
  color:var(--text);
  font-size:15px;
}

.highlight{
  color:var(--highlight);
  font-weight:800;
}

.grid{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:14px;
}

.field{
  display:flex;
  flex-direction:column;
  gap:8px;
}

.label{
  font-size:14px;
  font-weight:800;
  color:var(--highlight);
}

.input{
  width:100%;
  min-height:50px;
  border:1px solid var(--line);
  border-radius:15px;
  padding:12px 14px;
  font-size:15px;
  font-weight:600;
  color:#0f2f36;
  background:#ffffff;
  outline:none;
  transition:.2s;
}

.input:focus{
  border-color:var(--d);
  box-shadow:0 0 0 4px rgba(0,106,122,.10);
}

.input[disabled]{
  background:#f5f8f9;
  color:#29444a;
  font-weight:700;
  cursor:not-allowed;
}

.btns{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  margin-top:18px;
}

.btn{
  border:none;
  border-radius:15px;
  padding:12px 18px;
  text-decoration:none;
  font-size:14px;
  font-weight:800;
  cursor:pointer;
  transition:.18s ease;
  display:inline-flex;
  align-items:center;
  justify-content:center;
}

.btn:hover{
  transform:translateY(-1px);
}

.btn1{
  background:linear-gradient(135deg,var(--d),var(--t));
  color:#fff;
}

.btn2{
  background:#fff;
  border:1px solid var(--line);
  color:var(--d);
}

.err{
  background:#fff4f4;
  border:1px solid #f1c7c7;
  color:#c62828;
  padding:14px 16px;
  border-radius:16px;
  margin-bottom:16px;
}

.ok{
  background:#edf9f0;
  border:1px solid #bce2c4;
  color:#166534;
  padding:14px 16px;
  border-radius:16px;
  margin-bottom:16px;
  line-height:1.9;
}

.code{
  direction:ltr;
  text-align:left;
  background:#f8fafc;
  border:1px solid #e5e7eb;
  border-radius:12px;
  padding:10px 12px;
  word-break:break-all;
  margin-top:10px;
  font-size:13px;
}

.meta{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:12px;
  margin-top:10px;
}

.meta-box{
  background:#f8fbfc;
  border:1px solid #dfeaec;
  border-radius:12px;
  padding:10px 12px;
}

.meta-label{
  color:#6b7d82;
  font-size:12px;
  margin-bottom:4px;
}

.meta-value{
  font-weight:800;
  color:#12343b;
}

@media (max-width:900px){
  .ss-wrap{
    padding:16px;
  }

  .grid,
  .meta{
    grid-template-columns:1fr;
  }
}
</style>

<div class="ss-wrap">
  <div class="card">
    <div class="head">
      <h1 style="margin:0;color:var(--highlight);font-size:24px;">
        إرسال العقد للتوقيع
      </h1>
    </div>

    <div class="body">
      <p class="top-note">
        العقد:
        <span class="highlight"><?= h($displayTitle !== '' ? $displayTitle : '—') ?></span>
        —
        العميل الحالي:
        <span class="highlight"><?= h($contract['client_name'] ?? '—') ?></span>
      </p>

      <?php if ($errors): ?>
        <div class="err">
          <ul style="margin:0;padding-right:18px;">
            <?php foreach ($errors as $e): ?>
              <li><?= h($e) ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php endif; ?>

      <?php if ($link !== ''): ?>
        <div class="ok">
          <?= h($messageOk !== '' ? $messageOk : 'تم إنشاء رابط التوقيع بنجاح.') ?>
          <div class="code"><?= h($link) ?></div>

          <?php if ($shortCode !== ''): ?>
            <div class="meta">
              <div class="meta-box">
                <div class="meta-label">الكود المختصر</div>
                <div class="meta-value"><?= h($shortCode) ?></div>
              </div>
              <div class="meta-box">
                <div class="meta-label">رقم العقد</div>
                <div class="meta-value"><?= h($displayNo !== '' ? $displayNo : '—') ?></div>
              </div>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>

      <form method="post" action="">
        <input type="hidden" name="contract_id" value="<?= (int)$contractId ?>">

        <div class="grid">
          <div class="field">
            <label class="label">اسم الموقّع</label>
            <input
              class="input"
              type="text"
              name="signer_name"
              value="<?= h($signerName) ?>"
              placeholder="اكتب اسم الموقّع"
            >
          </div>

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

          <div class="field">
            <label class="label">الهاتف</label>
            <input
              class="input"
              type="text"
              name="signer_phone"
              value="<?= h($signerPhone) ?>"
              placeholder="05xxxxxxxx"
            >
          </div>

          <div class="field">
            <label class="label">رقم العقد</label>
            <input
              class="input"
              type="text"
              value="<?= h($displayNo !== '' ? $displayNo : '—') ?>"
              disabled
            >
          </div>
        </div>

        <div class="btns">
          <button class="btn btn1" type="submit">إنشاء رابط التوقيع</button>
          <a class="btn btn2" href="../view_contract.php?id=<?= (int)$contractId ?>">رجوع للعقد</a>
        </div>
      </form>
    </div>
  </div>
</div>

<?php render_layout_end(); ?>