<?php
declare(strict_types=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;
}

if (!isset($_SESSION['contract_generator_data']) || !is_array($_SESSION['contract_generator_data'])) {
    header('Location: fill_data.php');
    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($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('renderContractTemplate')) {
    function renderContractTemplate(string $templateHtml, array $data): string
    {
        foreach ($data as $key => $value) {
            $templateHtml = str_replace('{' . $key . '}', (string)$value, $templateHtml);
        }
        return $templateHtml;
    }
}

if (!function_exists('branch_name_ar_simple')) {
    function branch_name_ar_simple(int $branchId): string
    {
        return match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'العين',
            default => 'الفرع الرئيسي',
        };
    }
}

if (!function_exists('fmtDateAr')) {
    function fmtDateAr(?string $date): string
    {
        if (!$date) {
            return '—';
        }

        $ts = strtotime($date);
        if (!$ts) {
            return (string)$date;
        }

        return date('Y-m-d', $ts);
    }
}

if (!function_exists('generateUniqueValue')) {
    function generateUniqueValue(PDO $pdo, string $column, string $prefix): string
    {
        for ($i = 0; $i < 20; $i++) {
            $value = $prefix . '-' . date('YmdHis') . '-' . random_int(100, 999);

            $st = $pdo->prepare("SELECT id FROM contracts WHERE {$column} = ? LIMIT 1");
            $st->execute([$value]);
            $exists = $st->fetchColumn();

            if (!$exists) {
                return $value;
            }

            usleep(100000);
        }

        return $prefix . '-' . date('YmdHis') . '-' . random_int(1000, 9999) . '-' . random_int(100, 999);
    }
}

$data = $_SESSION['contract_generator_data'];

$userId         = (int)($_SESSION['user_id'] ?? 0);
$clientId       = (int)($data['client_id'] ?? 0);
$templateId     = (int)($data['template_id'] ?? 0);
$lawyerId       = (int)($data['lawyer_id'] ?? 0);
$contractTypeId = (int)($data['contract_type_id'] ?? 0);
$branchId       = (int)($data['branch_id'] ?? 0);

$title     = trim((string)($data['title'] ?? ''));
$amount    = (float)($data['amount'] ?? 0);
$startDate = trim((string)($data['start_date'] ?? ''));
$endDate   = trim((string)($data['end_date'] ?? ''));
$subject   = trim((string)($data['subject'] ?? ''));
$notes     = trim((string)($data['notes'] ?? ''));

$errors = [];

try {
    $st = $pdo->prepare("SELECT * FROM clients WHERE id = ? LIMIT 1");
    $st->execute([$clientId]);
    $client = $st->fetch();
} catch (Throwable $e) {
    $client = false;
}

if (!$client) {
    $errors[] = 'تعذر العثور على بيانات العميل.';
}

try {
    $st = $pdo->prepare("SELECT * FROM contract_templates WHERE id = ? AND is_active = 1 LIMIT 1");
    $st->execute([$templateId]);
    $template = $st->fetch();
} catch (Throwable $e) {
    $template = false;
}

if (!$template) {
    $errors[] = 'تعذر العثور على قالب العقد.';
}

$lawyer = null;
if ($lawyerId > 0) {
    try {
        $st = $pdo->prepare("SELECT * FROM employees WHERE id = ? LIMIT 1");
        $st->execute([$lawyerId]);
        $lawyer = $st->fetch();
    } catch (Throwable $e) {
        $lawyer = null;
    }
}

$contractType = null;
if ($contractTypeId > 0) {
    try {
        $st = $pdo->prepare("SELECT * FROM contract_types WHERE id = ? LIMIT 1");
        $st->execute([$contractTypeId]);
        $contractType = $st->fetch();
    } catch (Throwable $e) {
        $contractType = null;
    }
}

$clientName       = trim((string)($client['name'] ?? $client['client_name'] ?? ''));
$clientEmail      = trim((string)($client['email'] ?? ''));
$clientPhone      = trim((string)($client['phone'] ?? $client['mobile'] ?? ''));
$clientAddress    = trim((string)($client['address'] ?? ''));
$clientIdNumber   = trim((string)($client['id_number'] ?? $client['emirates_id'] ?? $client['passport_no'] ?? ''));
$lawyerName       = trim((string)($lawyer['full_name'] ?? ''));
$branchName       = branch_name_ar_simple($branchId);
$contractTypeName = trim((string)($contractType['contract_name'] ?? ''));
$templateBody     = (string)($template['body_html'] ?? '');

$startTs = ($startDate !== '') ? strtotime($startDate) : false;
$endTs   = ($endDate !== '') ? strtotime($endDate) : false;

if ($startDate === '') {
    $errors[] = 'تاريخ بداية العقد غير متوفر.';
}

if ($endDate === '') {
    $errors[] = 'تاريخ نهاية العقد غير متوفر.';
}

if ($startTs && $endTs && $endTs < $startTs) {
    $errors[] = 'تاريخ نهاية العقد يجب أن يكون بعد تاريخ البداية.';
}

if ($title === '') {
    $errors[] = 'عنوان العقد غير متوفر.';
}

if ($clientName === '') {
    $errors[] = 'اسم العميل غير متوفر.';
}

$contractNo = generateUniqueValue($pdo, 'contract_no', 'CT');
$transactionId = generateUniqueValue($pdo, 'transaction_id', 'TRX');

$templateVars = [
    'contract_no'      => $contractNo,
    'contract_date'    => date('Y-m-d'),
    'client_name'      => $clientName,
    'client_email'     => $clientEmail,
    'client_phone'     => $clientPhone,
    'client_address'   => $clientAddress,
    'client_id_number' => $clientIdNumber,
    'lawyer_name'      => $lawyerName,
    'branch_name'      => $branchName,
    'contract_type'    => $contractTypeName,
    'title'            => $title,
    'subject'          => $subject,
    'amount'           => number_format($amount, 2),
    'start_date'       => $startDate,
    'end_date'         => $endDate,
    'notes'            => nl2br(h($notes)),
];

$generatedHtml = $templateBody !== '' ? renderContractTemplate($templateBody, $templateVars) : '';

if (trim($generatedHtml) === '') {
    $errors[] = 'لا يمكن توليد نص العقد لأن القالب فارغ أو غير صالح.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_draft'])) {
    if (!$errors) {
        try {
            $pdo->beginTransaction();

            $insert = $pdo->prepare("
                INSERT INTO contracts
                (
                    contract_no,
                    transaction_id,
                    client_id,
                    lawyer_id,
                    branch_id,
                    contract_type_id,
                    template_id,
                    title,
                    contract_name,
                    subject,
                    amount,
                    start_date,
                    end_date,
                    notes,
                    status,
                    content_html,
                    created_by,
                    client_name,
                    mobile,
                    phone,
                    email,
                    contract_type,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()
                )
            ");

            $insert->execute([
                $contractNo,
                $transactionId,
                $clientId > 0 ? $clientId : null,
                $lawyerId > 0 ? $lawyerId : null,
                $branchId > 0 ? $branchId : null,
                $contractTypeId > 0 ? $contractTypeId : null,
                $templateId > 0 ? $templateId : null,
                $title !== '' ? $title : null,
                $title !== '' ? $title : null,
                $subject !== '' ? $subject : null,
                $amount,
                $startDate !== '' ? $startDate : null,
                $endDate !== '' ? $endDate : null,
                $notes !== '' ? $notes : null,
                'draft',
                $generatedHtml,
                $userId > 0 ? $userId : null,
                $clientName !== '' ? $clientName : null,
                $clientPhone !== '' ? $clientPhone : null,
                $clientPhone !== '' ? $clientPhone : null,
                $clientEmail !== '' ? $clientEmail : null,
                $contractTypeName !== '' ? $contractTypeName : null,
            ]);

            $contractId = (int)$pdo->lastInsertId();

            try {
                $log = $pdo->prepare("
                    INSERT INTO contract_logs
                    (contract_id, action, notes, action_by, created_at)
                    VALUES
                    (?, ?, ?, ?, NOW())
                ");

                $log->execute([
                    $contractId,
                    'created_draft',
                    'تم إنشاء العقد كمسودة من القالب: ' . trim((string)($template['template_name'] ?? '')),
                    $userId > 0 ? $userId : null
                ]);
            } catch (Throwable $e) {
                // لا نفشل العملية الأساسية إذا كان جدول السجل مختلفًا
            }

            $pdo->commit();

            unset($_SESSION['contract_generator_data']);

            header('Location: ../view_contract.php?id=' . $contractId . '&created=1');
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = 'حدث خطأ أثناء حفظ العقد كمسودة: ' . $e->getMessage();
        }
    }
}

render_layout_start('معاينة العقد');
?>

<style>
:root{
    --hlg-dark:#0b3440;
    --hlg-teal:#0a6474;
    --hlg-teal-2:#0e7688;
    --hlg-gold:#d4af37;
    --hlg-card:#ffffff;
    --hlg-bg:#f4f8fa;
    --hlg-soft:#f7fbfc;
    --hlg-line:#dce7eb;
    --hlg-text:#17343b;
    --hlg-muted:#708288;
    --hlg-danger:#b42318;
    --hlg-danger-bg:#fff3f2;
    --hlg-warn:#7a5a08;
    --hlg-warn-bg:#fffaf0;
    --hlg-shadow:0 18px 44px rgba(0,66,79,.10);
}

.cp-wrap{
    direction:rtl;
    font-family:'Tajawal',sans-serif;
    padding:22px;
    max-width:1280px;
    margin:0 auto;
    color:var(--hlg-text);
}

.cp-hero{
    position:relative;
    overflow:hidden;
    background:linear-gradient(135deg, var(--hlg-dark) 0%, var(--hlg-teal) 58%, var(--hlg-teal-2) 100%);
    color:#fff;
    border-radius:30px;
    padding:26px 28px;
    box-shadow:var(--hlg-shadow);
    margin-bottom:18px;
}

.cp-hero::before{
    content:"";
    position:absolute;
    left:-45px;
    bottom:-65px;
    width:200px;
    height:200px;
    border-radius:50%;
    background:rgba(255,255,255,.06);
}

.cp-hero::after{
    content:"";
    position:absolute;
    right:-40px;
    top:-50px;
    width:220px;
    height:220px;
    border-radius:50%;
    background:rgba(255,255,255,.05);
}

.cp-hero-inner{
    position:relative;
    z-index:2;
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:18px;
    flex-wrap:wrap;
}

.cp-hero-text h1{
    margin:0 0 10px;
    font-size:34px;
    line-height:1.2;
    font-weight:800;
}

.cp-hero-text p{
    margin:0;
    font-size:15px;
    line-height:2;
    opacity:.97;
    max-width:860px;
}

.cp-hero-badge{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:9px 14px;
    border-radius:999px;
    background:rgba(255,255,255,.11);
    border:1px solid rgba(255,255,255,.12);
    font-size:13px;
    font-weight:700;
    white-space:nowrap;
}

.cp-hero-badge-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--hlg-gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.16);
}

.cp-summary-grid{
    display:grid;
    grid-template-columns:repeat(3, minmax(0, 1fr));
    gap:14px;
    margin-bottom:18px;
}

.cp-stat{
    background:var(--hlg-card);
    border:1px solid var(--hlg-line);
    border-radius:22px;
    box-shadow:var(--hlg-shadow);
    padding:16px 16px 14px;
    min-height:104px;
}

.cp-stat-label{
    color:var(--hlg-muted);
    font-size:12px;
    margin-bottom:8px;
}

.cp-stat-value{
    color:var(--hlg-text);
    font-size:15px;
    font-weight:800;
    line-height:1.9;
    word-break:break-word;
}

.cp-main-card{
    background:var(--hlg-card);
    border:1px solid var(--hlg-line);
    border-radius:28px;
    box-shadow:var(--hlg-shadow);
    overflow:hidden;
}

.cp-toolbar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    flex-wrap:wrap;
    padding:18px 22px;
    border-bottom:1px solid #e8f0f2;
    background:linear-gradient(to left, #ffffff, #f8fbfc);
}

.cp-toolbar-title{
    margin:0;
    color:var(--hlg-dark);
    font-size:24px;
    font-weight:800;
}

.cp-toolbar-sub{
    margin:5px 0 0;
    color:var(--hlg-muted);
    font-size:13px;
}

.cp-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

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

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

.cp-btn-primary{
    background:linear-gradient(135deg, var(--hlg-dark) 0%, var(--hlg-teal) 100%);
    color:#fff;
    box-shadow:0 12px 24px rgba(0,66,79,.18);
}

.cp-btn-light{
    background:#fff;
    color:var(--hlg-dark);
    border:1px solid var(--hlg-line);
}

.cp-btn-print{
    background:#fff8e6;
    color:#7f5b00;
    border:1px solid #efd98f;
}

.cp-content{
    padding:22px;
    background:var(--hlg-soft);
}

.cp-errors{
    background:var(--hlg-danger-bg);
    border:1px solid #f0c8c4;
    color:var(--hlg-danger);
    border-radius:18px;
    padding:14px 16px;
    margin-bottom:16px;
}

.cp-errors ul{
    margin:0;
    padding:0 18px 0 0;
}

.cp-doc-shell{
    background:#eef5f7;
    border:1px solid #e1ecef;
    border-radius:24px;
    padding:18px;
}

.cp-doc{
    background:#fff;
    border:1px solid #dce7eb;
    border-radius:22px;
    padding:38px 34px;
    min-height:520px;
    color:#17323a;
    line-height:2.05;
    font-size:17px;
    box-shadow:0 8px 24px rgba(0,0,0,.03);
    max-width:980px;
    margin:0 auto;
}

.cp-doc h1,
.cp-doc h2,
.cp-doc h3,
.cp-doc h4{
    color:var(--hlg-dark);
    margin-top:0;
    margin-bottom:18px;
    text-align:center;
}

.cp-doc p{
    margin:0 0 14px;
}

.cp-doc table{
    width:100%;
    border-collapse:collapse;
    margin:14px 0;
}

.cp-doc table td,
.cp-doc table th{
    border:1px solid #dde7ea;
    padding:10px;
}

.cp-note{
    margin-top:16px;
    background:var(--hlg-warn-bg);
    border:1px solid #f0e0ae;
    border-radius:18px;
    padding:14px 16px;
    color:var(--hlg-warn);
    line-height:1.9;
    font-size:14px;
}

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

    .cp-hero{
        padding:22px 18px;
        border-radius:24px;
    }

    .cp-hero-text h1{
        font-size:26px;
    }

    .cp-summary-grid{
        grid-template-columns:repeat(1, minmax(0, 1fr));
    }

    .cp-toolbar{
        padding:16px;
    }

    .cp-toolbar-title{
        font-size:20px;
    }

    .cp-content{
        padding:16px;
    }

    .cp-doc-shell{
        padding:12px;
    }

    .cp-doc{
        padding:22px 16px;
        font-size:16px;
        min-height:360px;
    }
}

@media print {
    .sidebar,
    .topbar,
    .cp-hero,
    .cp-summary-grid,
    .cp-toolbar,
    .cp-note,
    .no-print{
        display:none !important;
    }

    body{
        background:#fff !important;
    }

    .cp-wrap,
    .cp-main-card,
    .cp-content,
    .cp-doc-shell,
    .cp-doc{
        margin:0 !important;
        padding:0 !important;
        border:none !important;
        box-shadow:none !important;
        background:#fff !important;
        max-width:100% !important;
    }
}
</style>

<div class="cp-wrap">
    <div class="cp-hero no-print">
        <div class="cp-hero-inner">
            <div class="cp-hero-text">
                <h1>معاينة العقد قبل الحفظ</h1>
                <p>راجع النص النهائي للعقد بعناية، ثم احفظه كمسودة داخل النظام قبل الانتقال لاحقًا إلى المراجعة والاعتماد والتوقيع الإلكتروني.</p>
            </div>

            <div class="cp-hero-badge">
                <span class="cp-hero-badge-dot"></span>
                <span>واجهة متوافقة مع HLG-ONE</span>
            </div>
        </div>
    </div>

    <div class="cp-summary-grid no-print">
        <div class="cp-stat">
            <div class="cp-stat-label">رقم العقد المقترح</div>
            <div class="cp-stat-value"><?= h($contractNo) ?></div>
        </div>

        <div class="cp-stat">
            <div class="cp-stat-label">العميل</div>
            <div class="cp-stat-value"><?= h($clientName) !== '' ? h($clientName) : '—' ?></div>
        </div>

        <div class="cp-stat">
            <div class="cp-stat-label">القالب</div>
            <div class="cp-stat-value"><?= !empty($template['template_name']) ? h($template['template_name']) : '—' ?></div>
        </div>

        <div class="cp-stat">
            <div class="cp-stat-label">المحامي المسؤول</div>
            <div class="cp-stat-value"><?= h($lawyerName) !== '' ? h($lawyerName) : '—' ?></div>
        </div>

        <div class="cp-stat">
            <div class="cp-stat-label">قيمة العقد</div>
            <div class="cp-stat-value"><?= h(number_format($amount, 2)) ?> د.إ</div>
        </div>

        <div class="cp-stat">
            <div class="cp-stat-label">الفترة</div>
            <div class="cp-stat-value">من <?= h(fmtDateAr($startDate)) ?> إلى <?= h(fmtDateAr($endDate)) ?></div>
        </div>
    </div>

    <div class="cp-main-card">
        <div class="cp-toolbar no-print">
            <div>
                <h2 class="cp-toolbar-title">نص العقد النهائي</h2>
                <div class="cp-toolbar-sub">هذه هي النسخة الناتجة من القالب بعد دمج بيانات العميل والعقد.</div>
            </div>

            <div class="cp-actions">
                <form method="post" style="margin:0;">
                    <button type="submit" name="save_draft" value="1" class="cp-btn cp-btn-primary">
                        حفظ كمسودة
                    </button>
                </form>

                <button type="button" class="cp-btn cp-btn-print" onclick="window.print()">طباعة</button>
                <a href="fill_data.php" class="cp-btn cp-btn-light">رجوع للتعديل</a>
            </div>
        </div>

        <div class="cp-content">
            <?php if ($errors): ?>
                <div class="cp-errors no-print">
                    <ul>
                        <?php foreach ($errors as $err): ?>
                            <li><?= h($err) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <div class="cp-doc-shell">
                <div class="cp-doc">
                    <?php if (!$errors && trim($generatedHtml) !== ''): ?>
                        <?= $generatedHtml ?>
                    <?php else: ?>
                        <p>لا يمكن عرض المعاينة حاليًا بسبب نقص البيانات أو مشكلة في القالب.</p>
                    <?php endif; ?>
                </div>
            </div>

            <div class="cp-note no-print">
                بعد حفظ العقد كمسودة، يمكنك لاحقًا ربطه بمرحلة المراجعة الداخلية ثم إرسال رابط التوقيع الإلكتروني للعميل.
            </div>
        </div>
    </div>
</div>

<?php render_layout_end(); ?>