<?php
// ========================================
// بازگشت از درگاه — شارژ کیف پول
// ========================================
session_start();
require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'payment/zarinpal.php';

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

if (empty($authority)) { header('Location: wallet.php?error=invalid'); exit; }

$stmt = $db->prepare("SELECT * FROM wallet_transactions WHERE authority = ? AND user_id = ? AND type = 'charge' LIMIT 1");
$stmt->execute([$authority, $user_id]);
$tx = $stmt->fetch();

if (!$tx) { header('Location: wallet.php?error=notfound'); exit; }
if ($tx['status'] === 'success') { header('Location: wallet.php?success=already'); exit; }

if ($status !== 'OK') {
    $db->prepare("UPDATE wallet_transactions SET status='failed' WHERE id=?")->execute([$tx['id']]);
    header('Location: wallet.php?error=canceled');
    exit;
}

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

if ($result['success']) {
    try {
        $db->beginTransaction();
        $db->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?")->execute([$tx['amount'], $user_id]);
        $newBalance = $db->query("SELECT wallet_balance FROM users WHERE id = $user_id")->fetchColumn();
        $db->prepare("UPDATE wallet_transactions SET status='success', ref_id=?, balance_after=?, description='شارژ کیف پول — کد پیگیری: ' || ? WHERE id=?")
           ->execute([$result['ref_id'], $newBalance, $result['ref_id'], $tx['id']]);
        $db->commit();
        Auth::logActivity('wallet_charge', 'شارژ کیف پول: ' . number_format($tx['amount']) . ' تومان | ref: ' . $result['ref_id']);
        header('Location: wallet.php?charged=' . $tx['amount']);
    } catch (Exception $e) {
        $db->rollBack();
        error_log("Wallet callback error: " . $e->getMessage());
        header('Location: wallet.php?error=system');
    }
} else {
    $db->prepare("UPDATE wallet_transactions SET status='failed' WHERE id=?")->execute([$tx['id']]);
    header('Location: wallet.php?error=payment_failed');
}
exit;
