<?php
// ========================================
// صفحه بازگشت از درگاه زرین‌پال - نسخه به‌روزشده
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once 'zarinpal.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$db       = Database::getInstance()->getConnection();
$settings = SiteSettings::getInstance();
$authority = $_GET['Authority'] ?? '';
$status    = $_GET['Status']    ?? '';

if (empty($authority)) {
    header('Location: ../cart.php?payment=failed');
    exit;
}

$stmt = $db->prepare("SELECT o.*, u.email, u.full_name FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.authority = ? LIMIT 1");
$stmt->execute([$authority]);
$order = $stmt->fetch();

if (!$order) {
    header('Location: ../cart.php?payment=failed&reason=notfound');
    exit;
}

if (!Auth::isLoggedIn() || $_SESSION['user_id'] != $order['user_id']) {
    header('Location: ../login.php');
    exit;
}

// کاربر پرداخت را لغو کرد
if ($status !== 'OK') {
    $db->prepare("UPDATE orders SET payment_status='unpaid', updated_at=NOW() WHERE id=?")->execute([$order['id']]);
    logPayment($db, $order['id'], 'cancel', 'cancelled', ['authority' => $authority]);
    header('Location: ../cart.php?payment=canceled');
    exit;
}

$merchantId  = $settings->get('zarinpal_merchant') ?: (defined('ZARINPAL_MERCHANT_ID') ? ZARINPAL_MERCHANT_ID : '');
$callbackUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/payment/callback.php';
$zarinpal    = new ZarinPal($merchantId, $callbackUrl);
$result      = $zarinpal->verify($authority, (int)$order['final_amount']);

if ($result['success']) {
    $db->prepare("UPDATE orders SET payment_status='paid', status='processing', ref_id=?, payment_date=NOW(), updated_at=NOW() WHERE id=?")
       ->execute([$result['ref_id'], $order['id']]);

    // لاگ پرداخت موفق
    logPayment($db, $order['id'], 'verify', 'success', [
        'authority' => $authority,
        'ref_id'    => $result['ref_id'],
        'amount'    => $order['final_amount'],
        'response'  => $result,
    ]);

    Auth::logActivity('payment_success', 'پرداخت موفق سفارش ' . $order['order_number'] . ' | ref: ' . $result['ref_id']);

    // ایمیل به کاربر
    emailUserPaymentSuccess($order['email'], $order['full_name'], $order, $result['ref_id']);

    // ایمیل به ادمین
    $itemsStmt = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
    $itemsStmt->execute([$order['id']]);
    emailAdminNewOrder($order, $itemsStmt->fetchAll());

    header('Location: ../order-success.php?id=' . $order['id'] . '&ref=' . $result['ref_id']);
} else {
    $db->prepare("UPDATE orders SET payment_status='unpaid', updated_at=NOW() WHERE id=?")->execute([$order['id']]);

    // لاگ پرداخت ناموفق
    logPayment($db, $order['id'], 'verify', 'failed', [
        'authority' => $authority,
        'amount'    => $order['final_amount'],
        'response'  => $result,
    ]);

    Auth::logActivity('payment_failed', 'پرداخت ناموفق سفارش ' . $order['order_number'] . ' | ' . $result['error']);

    header('Location: ../order-success.php?id=' . $order['id'] . '&payment=failed&reason=' . urlencode($result['error']));
}
exit;
