<?php
header('Content-Type: text/html; charset=utf-8');

$DB_HOST = 'localhost';
$DB_NAME = 'pnartli1_doorkar';
$DB_USER = 'pnartli1_doorkar';
$DB_PASS = 'V[B5S(1gO,OIqPvz';

$SEP_TERMINAL_ID = '15546670';
$SEP_VERIFY_URL = 'https://sep.shaparak.ir/verifyTxnRandomSessionkey/ipg/VerifyTransaction';
$SEP_AMOUNT_MULTIPLIER = 10; // مبلغ‌های داخلی تومان هستند و سپ معمولاً ریال برمی‌گرداند.
$AUTO_RETURN_SECONDS = 15;

function callback_debug_log($title, $data = []) {
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $title . ' ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
    @file_put_contents(__DIR__ . '/sep_callback_debug.log', $line, FILE_APPEND);
}

function post_json($url, $payload) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'DoorKar-SEP-Callback/1.0',
        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
    ]);
    $body = curl_exec($ch);
    $error = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $json = json_decode((string)$body, true);
    return [
        'http_code' => $code,
        'body' => $body,
        'json' => is_array($json) ? $json : null,
        'error' => $error,
    ];
}

function safe_html($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function fa_digits($value) {
    $en = ['0','1','2','3','4','5','6','7','8','9'];
    $fa = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    return str_replace($en, $fa, (string)$value);
}

function format_money_toman($amount) {
    $amount = (int)$amount;
    if ($amount <= 0) return '۰ تومان';
    return fa_digits(number_format($amount)) . ' تومان';
}

function payment_return_screen($payment) {
    $raw = '';
    if (is_array($payment) && isset($payment['token_response'])) {
        $decoded = json_decode((string)$payment['token_response'], true);
        if (is_array($decoded)) {
            $raw = trim((string)($decoded['return_screen'] ?? $decoded['source_screen'] ?? ''));
        }
    }
    return $raw === 'project_management' ? 'project_management' : 'create_project';
}

function finish_page($status, $message, $projectId = 0, $paymentId = 0, $amount = 0, $refNum = '', $traceNo = '', $extra = []) {
    global $AUTO_RETURN_SECONDS;

    $status = $status === 'paid' ? 'paid' : 'failed';
    $isPaid = $status === 'paid';

    $resNum = trim((string)($extra['res_num'] ?? ''));
    $rrn = trim((string)($extra['rrn'] ?? ''));
    $securePan = trim((string)($extra['secure_pan'] ?? ''));
    $stateText = trim((string)($extra['state_text'] ?? ''));
    $sepStatus = trim((string)($extra['sep_status'] ?? ''));
    $verifyAmount = (int)($extra['verified_amount'] ?? 0);

    $returnScreen = trim((string)($extra['return_screen'] ?? 'create_project'));
    $deepLinkHost = $returnScreen === 'project_management' ? 'project-management-payment-result' : 'payment-result';

    $queryParams = [
        'status' => $status,
        'message' => $message,
        'project_id' => (int)$projectId,
        'payment_id' => (int)$paymentId,
        'amount' => (int)$amount,
        'ref_num' => $refNum,
        'trace_no' => $traceNo,
        'res_num' => $resNum,
        'rrn' => $rrn,
        'return_screen' => $returnScreen,
    ];

    $deepLink = 'doorkar://' . $deepLinkHost . '?' . http_build_query($queryParams, '', '&', PHP_QUERY_RFC3986);
    $safeDeepLink = safe_html($deepLink);
    $safeMessage = safe_html($message);

    $title = $isPaid ? 'پرداخت با موفقیت تأیید شد' : 'پرداخت ناموفق بود';
    $subtitle = $isPaid
        ? 'رسید پرداخت ثبت شد. تا چند ثانیه دیگر به اپلیکیشن برمی‌گردی.'
        : 'پرداخت تکمیل نشد یا توسط درگاه تأیید نشد. جزئیات زیر را برای پیگیری نگه دار.';

    $themeMain = $isPaid ? '#18A957' : '#E5484D';
    $themeSoft = $isPaid ? '#EAF9F0' : '#FFF1F2';
    $themeBorder = $isPaid ? '#BFEBD0' : '#FFD0D3';
    $icon = $isPaid ? '✓' : '×';

    $details = [];
    if ((int)$projectId > 0) $details[] = ['شماره پروژه', fa_digits((string)$projectId)];
    if ((int)$paymentId > 0) $details[] = ['شناسه پرداخت داخلی', fa_digits((string)$paymentId)];
    if ((int)$amount > 0) $details[] = ['مبلغ پرداختی', format_money_toman($amount)];
    if ($resNum !== '') $details[] = ['شناسه سفارش', fa_digits($resNum)];
    if ($refNum !== '') $details[] = ['رسید دیجیتال درگاه', fa_digits($refNum)];
    if ($traceNo !== '') $details[] = ['کد پیگیری', fa_digits($traceNo)];
    if ($rrn !== '') $details[] = ['شماره مرجع بانکی', fa_digits($rrn)];
    if ($securePan !== '') $details[] = ['کارت پرداخت', fa_digits($securePan)];
    if ($verifyAmount > 0) $details[] = ['مبلغ تأییدشده درگاه', fa_digits(number_format($verifyAmount)) . ' ریال'];
    if (!$isPaid && $stateText !== '') $details[] = ['وضعیت درگاه', fa_digits($stateText)];
    if (!$isPaid && $sepStatus !== '') $details[] = ['کد وضعیت سپ', fa_digits($sepStatus)];

    $detailHtml = '';
    if (!empty($details)) {
        foreach ($details as $row) {
            $detailHtml .= "<div class='detail-row'><span class='detail-label'>" . safe_html($row[0]) . "</span><span class='detail-value'>" . safe_html($row[1]) . "</span></div>";
        }
    } else {
        $detailHtml = "<div class='empty-detail'>جزئیات تراکنش از درگاه دریافت نشد.</div>";
    }

    $helpText = $isPaid
        ? 'در صورت نیاز به پیگیری، رسید دیجیتال و کد پیگیری را نگه دار.'
        : 'اگر مبلغ از حساب کم شده باشد، معمولاً طبق روال بانکی برگشت می‌خورد. برای پیگیری، شناسه سفارش، مبلغ و زمان پرداخت را نگه دار.';

    $countdown = max(5, (int)$AUTO_RETURN_SECONDS);

    echo "<!doctype html>
<html lang='fa' dir='rtl'>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1'>
    <title>نتیجه پرداخت</title>
    <style>
        @font-face {
            font-family: 'VazirDoorKar';
            src: url('/doorkar/fonts/vazirlightfd.ttf') format('truetype'),
                 url('fonts/vazirlightfd.ttf') format('truetype'),
                 url('./vazirlightfd.ttf') format('truetype');
            font-weight: normal;
            font-style: normal;
            font-display: swap;
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            min-height: 100vh;
            font-family: 'VazirDoorKar', Tahoma, Arial, sans-serif;
            background:
                radial-gradient(circle at 20% 0%, rgba(24,169,87,0.10), transparent 32%),
                linear-gradient(180deg, #F5FAF7 0%, #EEF4F1 100%);
            color: #1E2621;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 18px;
        }
        .page {
            width: 100%;
            max-width: 460px;
        }
        .card {
            background: #FFFFFF;
            border: 1px solid #E1E9E4;
            border-radius: 28px;
            box-shadow: 0 18px 50px rgba(27, 43, 34, 0.10);
            overflow: hidden;
        }
        .top {
            padding: 24px 20px 18px;
            text-align: center;
            background: linear-gradient(180deg, " . safe_html($themeSoft) . " 0%, #FFFFFF 88%);
        }
        .icon {
            width: 70px;
            height: 70px;
            margin: 0 auto 14px;
            border-radius: 25px;
            background: " . safe_html($themeMain) . ";
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 38px;
            font-weight: 900;
            box-shadow: 0 12px 28px " . safe_html($themeBorder) . ";
        }
        h1 {
            margin: 0;
            font-size: 21px;
            line-height: 1.9;
            color: #1E2621;
            font-weight: 900;
        }
        .subtitle {
            margin: 8px 0 0;
            color: #66736B;
            font-size: 13px;
            line-height: 2.1;
        }
        .message-box {
            margin: 16px 18px 0;
            padding: 13px 14px;
            border-radius: 18px;
            border: 1px solid " . safe_html($themeBorder) . ";
            background: " . safe_html($themeSoft) . ";
            color: " . safe_html($themeMain) . ";
            font-size: 13px;
            line-height: 2;
            text-align: center;
            font-weight: 700;
        }
        .section {
            padding: 18px;
        }
        .section-title {
            font-size: 15px;
            font-weight: 900;
            margin-bottom: 12px;
            color: #1E2621;
        }
        .details {
            border: 1px solid #E5ECE8;
            border-radius: 20px;
            overflow: hidden;
            background: #FBFDFC;
        }
        .detail-row {
            display: flex;
            gap: 12px;
            justify-content: space-between;
            align-items: center;
            padding: 13px 14px;
            border-bottom: 1px solid #EAF0ED;
        }
        .detail-row:last-child { border-bottom: 0; }
        .detail-label {
            color: #6D7971;
            font-size: 12px;
            white-space: nowrap;
        }
        .detail-value {
            color: #1E2621;
            font-size: 12.5px;
            font-weight: 900;
            text-align: left;
            direction: ltr;
            word-break: break-word;
        }
        .empty-detail {
            color: #7B8780;
            font-size: 13px;
            line-height: 2;
            padding: 16px;
            text-align: center;
        }
        .help {
            margin-top: 12px;
            padding: 12px 13px;
            border-radius: 17px;
            background: #F7FAF8;
            color: #6D7971;
            font-size: 12px;
            line-height: 2;
            border: 1px solid #E6EEE9;
        }
        .actions {
            padding: 0 18px 18px;
        }
        .return-btn {
            display: block;
            width: 100%;
            border: 0;
            border-radius: 18px;
            background: #18A957;
            color: #FFFFFF;
            text-decoration: none;
            text-align: center;
            padding: 15px 14px;
            font-size: 14px;
            font-weight: 900;
            box-shadow: 0 10px 24px rgba(24,169,87,0.25);
        }
        .countdown {
            margin-top: 12px;
            text-align: center;
            color: #738079;
            font-size: 12px;
            line-height: 2;
        }
        .count-number {
            display: inline-flex;
            width: 30px;
            height: 30px;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            background: #EEF7F1;
            color: #18A957;
            font-weight: 900;
            margin: 0 4px;
        }
        .footer-note {
            text-align: center;
            margin-top: 12px;
            color: #99A49E;
            font-size: 11px;
            line-height: 1.9;
        }
    </style>
</head>
<body>
    <main class='page'>
        <section class='card'>
            <div class='top'>
                <div class='icon'>" . safe_html($icon) . "</div>
                <h1>" . safe_html($title) . "</h1>
                <p class='subtitle'>" . safe_html($subtitle) . "</p>
            </div>

            <div class='message-box'>" . $safeMessage . "</div>

            <div class='section'>
                <div class='section-title'>جزئیات تراکنش</div>
                <div class='details'>" . $detailHtml . "</div>
                <div class='help'>" . safe_html($helpText) . "</div>
            </div>

            <div class='actions'>
                <a class='return-btn' id='returnButton' href='" . $safeDeepLink . "'>بازگشت به اپلیکیشن</a>
                <div class='countdown'>بازگشت خودکار تا <span class='count-number' id='countdown'>" . fa_digits((string)$countdown) . "</span> ثانیه دیگر</div>
            </div>
        </section>
        <div class='footer-note'>DoorKar Payment Result</div>
    </main>

    <script>
        (function () {
            var deepLink = " . json_encode($deepLink, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ";
            var seconds = " . (int)$countdown . ";
            var el = document.getElementById('countdown');
            var fa = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
            function toFa(value) {
                return String(value).replace(/[0-9]/g, function (d) { return fa[Number(d)]; });
            }
            function goBackToApp() {
                window.location.href = deepLink;
            }
            document.getElementById('returnButton').addEventListener('click', function () {
                setTimeout(goBackToApp, 50);
            });
            var timer = setInterval(function () {
                seconds -= 1;
                if (seconds <= 0) {
                    clearInterval(timer);
                    goBackToApp();
                    return;
                }
                if (el) el.textContent = toFa(seconds);
            }, 1000);
        })();
    </script>
</body>
</html>";
    exit;
}

try {
    $pdo = new PDO(
        "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4",
        $DB_USER,
        $DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (Throwable $e) {
    callback_debug_log('db_connection_failed', ['error' => $e->getMessage()]);
    finish_page('failed', 'اتصال به دیتابیس برقرار نشد. لطفاً چند دقیقه بعد دوباره بررسی کن.');
}

$payload = array_merge($_GET, $_POST);

$resNum = trim((string)($payload['ResNum'] ?? ''));
$refNum = trim((string)($payload['RefNum'] ?? ''));
$state = trim((string)($payload['State'] ?? ''));
$status = trim((string)($payload['Status'] ?? ''));
$traceNo = trim((string)($payload['TraceNo'] ?? ''));
$securePan = trim((string)($payload['SecurePan'] ?? ''));
$hashedCard = trim((string)($payload['HashedCardNumber'] ?? ''));

callback_debug_log('callback_received', [
    'res_num' => $resNum,
    'ref_num' => $refNum,
    'state' => $state,
    'status' => $status,
    'trace_no' => $traceNo,
    'payload' => $payload,
]);

if ($resNum === '') {
    finish_page('failed', 'شناسه سفارش از سمت درگاه دریافت نشد.', 0, 0, 0, $refNum, $traceNo, [
        'state_text' => $state,
        'sep_status' => $status,
        'secure_pan' => $securePan,
    ]);
}

$stmt = $pdo->prepare("SELECT * FROM project_payments WHERE res_num=? ORDER BY id DESC LIMIT 1");
$stmt->execute([$resNum]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$payment) {
    callback_debug_log('payment_not_found', ['res_num' => $resNum, 'payload' => $payload]);
    finish_page('failed', 'پرداخت مربوط به این شناسه سفارش در سیستم پیدا نشد.', 0, 0, 0, $refNum, $traceNo, [
        'res_num' => $resNum,
        'state_text' => $state,
        'sep_status' => $status,
        'secure_pan' => $securePan,
    ]);
}

$paymentId = (int)$payment['id'];
$projectId = (int)$payment['project_id'];
$amount = (int)$payment['amount'];
$returnScreen = payment_return_screen($payment);

$pdo->prepare("UPDATE project_payments
    SET callback_payload=?, state_text=?, sep_status=?, ref_num=?, trace_no=?, secure_pan=?, hashed_card_number=?, status='callback_received'
    WHERE id=? LIMIT 1")
    ->execute([
        json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        $state,
        $status,
        $refNum,
        $traceNo,
        $securePan,
        $hashedCard,
        $paymentId,
    ]);

$gatewaySaysOk = ($status === '2' || strtolower($state) === 'ok');

if ($refNum === '' || !$gatewaySaysOk) {
    $pdo->prepare("UPDATE project_payments SET status='failed' WHERE id=? LIMIT 1")->execute([$paymentId]);
    $pdo->prepare("UPDATE projects SET payment_status='failed' WHERE id=? LIMIT 1")->execute([$projectId]);

    finish_page('failed', 'پرداخت ناموفق یا لغوشده است.', $projectId, $paymentId, $amount, $refNum, $traceNo, [
        'res_num' => $resNum,
        'state_text' => $state,
        'sep_status' => $status,
        'secure_pan' => $securePan,
        'return_screen' => $returnScreen,
    ]);
}

$verifyPayload = [
    'RefNum' => $refNum,
    'TerminalNumber' => (int)$SEP_TERMINAL_ID,
];

$verify = post_json($SEP_VERIFY_URL, $verifyPayload);
$verifyJson = $verify['json'];

callback_debug_log('verify_response', [
    'payment_id' => $paymentId,
    'project_id' => $projectId,
    'request' => $verifyPayload,
    'http_code' => $verify['http_code'],
    'error' => $verify['error'],
    'response' => $verifyJson,
]);

$success = is_array($verifyJson)
    && !empty($verifyJson['Success'])
    && (int)($verifyJson['ResultCode'] ?? -1) === 0;

$detail = [];
if (is_array($verifyJson) && isset($verifyJson['TransactionDetail']) && is_array($verifyJson['TransactionDetail'])) {
    $detail = $verifyJson['TransactionDetail'];
}

$verifiedAmount = (int)($detail['AffectiveAmount'] ?? $detail['OrginalAmount'] ?? $detail['OriginalAmount'] ?? 0);
$expectedAmount = $amount * $SEP_AMOUNT_MULTIPLIER;
$verifyTraceNo = trim((string)($detail['StraceNo'] ?? $detail['TraceNo'] ?? $traceNo));
$rrn = trim((string)($detail['RRN'] ?? ''));

if (!$success || $verifiedAmount !== $expectedAmount) {
    $pdo->prepare("UPDATE project_payments SET status='verify_failed', verify_response=? WHERE id=? LIMIT 1")
        ->execute([
            json_encode([
                'request' => $verifyPayload,
                'response' => $verifyJson,
                'http_code' => $verify['http_code'],
                'error' => $verify['error'],
                'expected_amount' => $expectedAmount,
                'verified_amount' => $verifiedAmount,
            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            $paymentId,
        ]);

    $pdo->prepare("UPDATE projects SET payment_status='verify_failed' WHERE id=? LIMIT 1")->execute([$projectId]);

    finish_page('failed', 'تأیید پرداخت توسط درگاه ناموفق بود.', $projectId, $paymentId, $amount, $refNum, $verifyTraceNo, [
        'res_num' => $resNum,
        'rrn' => $rrn,
        'secure_pan' => $securePan,
        'state_text' => $state,
        'sep_status' => $status,
        'verified_amount' => $verifiedAmount,
        'return_screen' => $returnScreen,
    ]);
}

$pdo->prepare("UPDATE project_payments
    SET status='paid', rrn=?, trace_no=?, verify_response=?, paid_at=NOW()
    WHERE id=? LIMIT 1")
    ->execute([
        $rrn,
        $verifyTraceNo,
        json_encode(['request' => $verifyPayload, 'response' => $verifyJson], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        $paymentId,
    ]);

$pdo->prepare("UPDATE projects
    SET status='open', payment_status='paid', payment_id=?, payment_ref_num=?, payment_trace_no=?, paid_at=NOW()
    WHERE id=? LIMIT 1")
    ->execute([$paymentId, $refNum, $verifyTraceNo, $projectId]);

finish_page('paid', 'پرداخت با موفقیت ثبت و تأیید شد.', $projectId, $paymentId, $amount, $refNum, $verifyTraceNo, [
    'res_num' => $resNum,
    'rrn' => $rrn,
    'secure_pan' => $securePan,
    'state_text' => $state,
    'sep_status' => $status,
    'verified_amount' => $verifiedAmount,
    'return_screen' => $returnScreen,
]);