<?php
declare(strict_types=1);

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

$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 [];
        }
    }
}

$token     = trim((string)($_GET['token'] ?? ''));
$shortCode = strtoupper(trim((string)($_GET['c'] ?? '')));

if ($token === '' && $shortCode === '') {
    exit('رابط غير صالح');
}

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

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

$contractNoExpr = in_array('contract_no', $contractCols, true)
    ? "c.contract_no"
    : (in_array('transaction_id', $contractCols, true) ? "c.transaction_id" : "CAST(c.id AS CHAR)");

$hasShortCode = in_array('short_code', $signReqCols, true);

$sql = "
    SELECT
        sr.*,
        {$titleExpr} AS title,
        {$contractNoExpr} AS contract_no,
        s.signature_file,
        s.signed_at AS signature_signed_at
    FROM contract_sign_requests sr
    JOIN contracts c ON c.id = sr.contract_id
    LEFT JOIN contract_signatures s ON s.sign_request_id = sr.id
";

if ($shortCode !== '') {
    if (!$hasShortCode) {
        exit('عمود short_code غير موجود في جدول طلبات التوقيع');
    }

    $st = $pdo->prepare($sql . " WHERE sr.short_code = ? LIMIT 1");
    $st->execute([$shortCode]);
} else {
    $st = $pdo->prepare($sql . " WHERE sr.sign_token = ? LIMIT 1");
    $st->execute([$token]);
}

$row = $st->fetch();
if (!$row) {
    exit('بيانات التوقيع غير موجودة');
}

$signedAt = trim((string)($row['signature_signed_at'] ?? $row['signed_at'] ?? ''));
if ($signedAt === '') {
    $signedAt = '—';
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>اكتمال التوقيع</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
:root{
  --d:#00424f;
  --t:#006a7a;
  --line:#dce8eb;
  --shadow:0 18px 42px rgba(0,66,79,.08);
}
*{box-sizing:border-box}
body{
  margin:0;
  background:#f5fafb;
  font-family:'Tajawal',sans-serif;
  color:#17323a;
}
.wrap{
  max-width:760px;
  margin:0 auto;
  padding:24px;
}
.card{
  background:#fff;
  border:1px solid var(--line);
  border-radius:24px;
  box-shadow:var(--shadow);
  padding:28px;
}
.ok{
  width:70px;
  height:70px;
  border-radius:50%;
  display:flex;
  align-items:center;
  justify-content:center;
  background:#edf9f0;
  color:#166534;
  font-size:34px;
  margin:0 auto 16px;
}
h1{
  margin:0 0 10px;
  color:var(--d);
  text-align:center;
}
p{
  line-height:1.9;
  text-align:center;
  margin:0;
}
.meta{
  display:grid;
  gap:12px;
  margin-top:20px;
}
.item{
  border:1px solid #e3ecef;
  border-radius:16px;
  padding:12px 14px;
  background:#fbfdfe;
}
.label{
  font-size:12px;
  color:#6b7d82;
}
.value{
  font-size:15px;
  font-weight:700;
  margin-top:4px;
  color:#17323a;
}
</style>
</head>
<body>
<div class="wrap">
  <div class="card">
    <div class="ok">✓</div>
    <h1>تم التوقيع بنجاح</h1>
    <p>شكرًا لك. تم استلام توقيعك الإلكتروني على العقد وحفظه داخل النظام.</p>

    <div class="meta">
      <div class="item">
        <div class="label">رقم العقد</div>
        <div class="value"><?= h($row['contract_no'] ?? '—') ?></div>
      </div>

      <div class="item">
        <div class="label">العقد</div>
        <div class="value"><?= h($row['title'] ?? '—') ?></div>
      </div>

      <div class="item">
        <div class="label">اسم الموقّع</div>
        <div class="value"><?= h($row['signer_name'] ?? '—') ?></div>
      </div>

      <div class="item">
        <div class="label">تاريخ التوقيع</div>
        <div class="value"><?= h($signedAt) ?></div>
      </div>

      <?php if (!empty($row['short_code'])): ?>
        <div class="item">
          <div class="label">الكود المختصر</div>
          <div class="value"><?= h($row['short_code']) ?></div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
</body>
</html>