<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

$db_host = 'localhost';
$db_name = 'violexst_bot';
$db_user = 'violexst_botuser';
$db_pass = 'ViolexBot#92!qR7@Lm';

$token = $_GET['token'] ?? '';
if (!$token) die('پیش‌فاکتور نامعتبر است.');

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) die('خطا در اتصال به دیتابیس.');
$conn->set_charset('utf8mb4');

$stmt = $conn->prepare("SELECT * FROM invoices WHERE token = ?");
$stmt->bind_param('s', $token);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();
$conn->close();

if (!$invoice) die('پیش‌فاکتور یافت نشد.');

$now = date('Y/m/d H:i:s');
$is_expired = $invoice['expires_at'] < $now && $invoice['status'] === 'pending';
$status = $invoice['status'];

if ($status === 'paid') {
    header('Location: /invoice/success.php?token=' . urlencode($token));
    exit;
}
if ($status === 'failed') {
    header('Location: /invoice/failed.php?token=' . urlencode($token));
    exit;
}
if ($is_expired) {
    header('Location: /invoice/failed.php?token=' . urlencode($token) . '&expired=1');
    exit;
}

if (empty($invoice['authority'])) {
    $ZIBAL_MERCHANT = '69e3945ee6d570ad00fd0dad';
    $CALLBACK_URL = 'https://violex.s12.telviprobot.top/api/verify.php';

    $data = [
        'merchant'    => $ZIBAL_MERCHANT,
        'amount'      => $invoice['total_amount'] * 10,
        'callbackUrl' => $CALLBACK_URL,
        'description' => $invoice['product_name'] . ' - ویولکس'
    ];

    $ch = curl_init('https://gateway.zibal.ir/v1/request');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($response, true);

    if (!isset($result['trackId'])) {
        die('خطا در ایجاد لینک پرداخت: ' . ($result['message'] ?? 'نامشخص'));
    }

    $authority = (string)$result['trackId'];

    $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
    $conn->set_charset('utf8mb4');
    $stmt = $conn->prepare("UPDATE invoices SET authority = ? WHERE token = ?");
    $stmt->bind_param('ss', $authority, $token);
    $stmt->execute();
    $stmt->close();
    $conn->close();

    $invoice['authority'] = $authority;
}

$payment_url = 'https://gateway.zibal.ir/start/' . $invoice['authority'];
$expires_ts = strtotime(str_replace('/', '-', $invoice['expires_at']));
$now_ts = time();
$remain_seconds = max(0, $expires_ts - $now_ts);
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>پیش‌فاکتور - ویولکس</title>
<style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
        font-family: Tahoma, Arial, sans-serif;
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 20px;
    }
    .card {
        background: white;
        border-radius: 24px;
        max-width: 550px;
        width: 100%;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        overflow: hidden;
    }
    .header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 30px;
        text-align: center;
    }
    .header h1 { font-size: 24px; margin-bottom: 8px; }
    .header p { font-size: 14px; opacity: 0.9; }
    .body { padding: 30px; }
    .invoice-no {
        text-align: center;
        background: #f5f7ff;
        border-radius: 12px;
        padding: 12px;
        margin-bottom: 20px;
        font-size: 13px;
        color: #555;
    }
    .invoice-no strong {
        color: #667eea;
        font-family: monospace;
        direction: ltr;
        display: inline-block;
        word-break: break-all;
    }
    .row {
        display: flex;
        justify-content: space-between;
        padding: 12px 0;
        border-bottom: 1px solid #eee;
        font-size: 15px;
    }
    .row:last-of-type { border-bottom: none; }
    .row .label { color: #888; }
    .row .value {
        color: #333;
        font-weight: bold;
        max-width: 60%;
        text-align: left;
        direction: ltr;
    }
    .total {
        background: #f0f4ff;
        border-radius: 12px;
        padding: 18px;
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .total .label { font-size: 16px; color: #333; }
    .total .amount { font-size: 22px; font-weight: bold; color: #667eea; }
    .timer {
        text-align: center;
        background: #fff3cd;
        border-radius: 12px;
        padding: 12px;
        margin-top: 20px;
        color: #856404;
        font-size: 14px;
    }
    .timer strong {
        font-family: monospace;
        font-size: 18px;
        color: #d39e00;
    }
    .pay-btn {
        display: block;
        width: 100%;
        padding: 18px;
        margin-top: 25px;
        background: linear-gradient(135deg, #4CAF50 0%, #2e7d32 100%);
        color: white;
        text-decoration: none;
        text-align: center;
        border-radius: 12px;
        font-size: 17px;
        font-weight: bold;
        box-shadow: 0 8px 20px rgba(76,175,80,0.3);
    }
    .back-btn {
        display: block;
        text-align: center;
        margin-top: 15px;
        color: #888;
        text-decoration: none;
        font-size: 14px;
    }
    .footer {
        text-align: center;
        padding: 15px;
        background: #fafafa;
        color: #999;
        font-size: 12px;
    }
</style>
</head>
<body>
<div style="text-align:center; padding:15px;">
<a referrerpolicy='origin' target='_blank' href='https://trustseal.enamad.ir/?id=716122&Code=z3z1UH6o6PgHsulQATp9NFkdz8lyxGYK'><img referrerpolicy='origin' src='https://trustseal.enamad.ir/logo.aspx?id=716122&Code=z3z1UH6o6PgHsulQATp9NFkdz8lyxGYK' alt='' style='cursor:pointer' code='z3z1UH6o6PgHsulQATp9NFkdz8lyxGYK'></a>
</div>
<div class="card">
    <div class="header">
        <h1>🧾 پیش‌فاکتور پرداخت</h1>
        <p>ویولکس | کلینیک رفع اشکال کنکور</p>
    </div>

    <div class="body">
        <div class="invoice-no">
            شماره فاکتور: <strong><?= htmlspecialchars($invoice['token']) ?></strong>
        </div>

        <div class="row">
            <span class="label">👤 نام واریز کننده:</span>
            <span class="value"><?= htmlspecialchars($invoice['payer_name']) ?></span>
        </div>
        <div class="row">
            <span class="label">📱 شماره تماس:</span>
            <span class="value"><?= htmlspecialchars($invoice['payer_phone']) ?></span>
        </div>
        <div class="row">
            <span class="label">📦 نام محصول:</span>
            <span class="value"><?= htmlspecialchars($invoice['product_name']) ?></span>
        </div>
        <div class="row">
            <span class="label">💰 قیمت واحد:</span>
            <span class="value"><?= number_format($invoice['price']) ?> تومان</span>
        </div>
        <div class="row">
            <span class="label">🔢 تعداد:</span>
            <span class="value"><?= $invoice['quantity'] ?></span>
        </div>

        <div class="total">
            <span class="label">💳 مبلغ قابل پرداخت:</span>
            <span class="amount"><?= number_format($invoice['total_amount']) ?> تومان</span>
        </div>

        <div class="timer">
            ⏰ زمان باقی‌مانده: <strong id="countdown"></strong>
        </div>

        <a href="<?= htmlspecialchars($payment_url) ?>" class="pay-btn">
            💳 پرداخت آنلاین با زیبال
        </a>
        <a href="https://t.me/VIOLEXQ_bot" class="back-btn">
            ← بازگشت به ربات
        </a>
    </div>

    <div class="footer">
        
        این پیش‌فاکتور تا ۱ ساعت معتبر است.
    </div>
</div>

<script>
    var remain = <?= $remain_seconds ?>;
    function tick() {
        if (remain <= 0) {
            document.getElementById('countdown').textContent = 'منقضی شده';
            document.querySelector('.pay-btn').style.display = 'none';
            return;
        }
        var m = Math.floor(remain / 60);
        var s = remain % 60;
        document.getElementById('countdown').textContent =
            (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
        remain--;
    }
    tick();
    setInterval(tick, 1000);
</script>
</body>
</html>