<?php
// verify-paystack.php
// Handles both user redirect (callback) and Paystack webhook (POST)

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../admin/includes/EmailService.php';

// ============================================================
// 1. DETERMINE REQUEST TYPE
// ============================================================
$is_webhook = ($_SERVER['REQUEST_METHOD'] === 'POST');

if ($is_webhook) {
    // --- WEBHOOK HANDLER ---
    $payload = @file_get_contents('php://input');
    $payload_data = json_decode($payload, true);

    // Verify webhook signature
    $stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'paystack_secret_key'");
    $secret_key = $stmt->fetchColumn();

    $signature = $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] ?? '';
    $computed = hash_hmac('sha512', $payload, $secret_key);

    if (!$signature || $signature !== $computed) {
        http_response_code(401);
        die('Invalid signature.');
    }

    // Only process 'charge.success' events
    if (($payload_data['event'] ?? '') !== 'charge.success') {
        http_response_code(200);
        exit('Ignored event');
    }

    $reference = $payload_data['data']['reference'] ?? null;
    $status = $payload_data['data']['status'] ?? null;

    if ($status !== 'success' || !$reference) {
        http_response_code(200);
        exit('Transaction not successful');
    }

    $result = processPayment($reference, $pdo);

    if ($result['success']) {
        http_response_code(200);
        echo 'Webhook processed successfully';
    } else {
        http_response_code(500);
        echo 'Error: ' . $result['message'];
    }
    exit;
}

// ============================================================
// 2. CALLBACK (GET) – User redirected after payment
// ============================================================
if (!isset($_GET['reference'])) {
    $_SESSION['error_msg'] = "Missing payment reference.";
    header("Location: ../user/billing.php");
    exit();
}

$reference = filter_input(INPUT_GET, 'reference', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

// Verify transaction via Paystack API
$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'paystack_secret_key'");
$secret_key = $stmt->fetchColumn();

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.paystack.co/transaction/verify/" . rawurlencode($reference));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . $secret_key,
    "Cache-Control: no-cache"
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    $_SESSION['error_msg'] = "Paystack Connection Error: " . $err;
    header("Location: ../user/billing.php");
    exit();
}

$tranx = json_decode($response, true);

if (!$tranx['status'] || $tranx['data']['status'] !== 'success') {
    $_SESSION['error_msg'] = "Payment verification failed or was cancelled.";
    header("Location: ../user/billing.php");
    exit();
}

// Process the payment
$result = processPayment($reference, $pdo);

if ($result['success']) {
    $_SESSION['success_msg'] = $result['message'];
} else {
    $_SESSION['error_msg'] = $result['message'];
}

header("Location: ../user/billing.php");
exit();

// ============================================================
// 3. SHARED PROCESSING FUNCTION
// ============================================================
function processPayment($reference, $pdo) {
    try {
        // Look up the pending payment
        $stmt = $pdo->prepare("SELECT * FROM pending_payments WHERE reference = ? AND status = 'pending'");
        $stmt->execute([$reference]);
        $pending = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$pending) {
            // Check if already processed
            $stmt = $pdo->prepare("SELECT * FROM pending_payments WHERE reference = ? AND status = 'processed'");
            $stmt->execute([$reference]);
            if ($stmt->fetch()) {
                return ['success' => true, 'message' => 'Payment already processed.'];
            }
            return ['success' => false, 'message' => 'Pending payment record not found.'];
        }

        $user_id = $pending['user_id'];
        $plan_id = $pending['plan_id'];
        $amount = $pending['amount'];

        // Get plan details
        $stmt = $pdo->prepare("SELECT plan_name, duration_days FROM subscription_plans WHERE id = ?");
        $stmt->execute([$plan_id]);
        $plan = $stmt->fetch(PDO::FETCH_ASSOC);
        $duration = $plan['duration_days'] ?? 30;
        $plan_name = $plan['plan_name'] ?? 'Subscription';

        // Begin database transaction
        $pdo->beginTransaction();

        // 1. Calculate expiry date
        $expiry_date = date('Y-m-d H:i:s', strtotime("+" . $duration . " days"));

        // 2. Update user_subscriptions table
        $sub_stmt = $pdo->prepare("
            INSERT INTO user_subscriptions (user_id, plan_id, expires_at, is_active) 
            VALUES (?, ?, ?, 1) 
            ON DUPLICATE KEY UPDATE 
                plan_id = VALUES(plan_id), 
                expires_at = VALUES(expires_at), 
                is_active = 1
        ");
        $sub_stmt->execute([$user_id, $plan_id, $expiry_date]);

        // 3. Update users table (user_tier and vip_expires_at)
        $user_stmt = $pdo->prepare("
            UPDATE users 
            SET user_tier = 'VIP', 
                vip_expires_at = CASE 
                    WHEN vip_expires_at > NOW() THEN DATE_ADD(vip_expires_at, INTERVAL ? DAY)
                    ELSE DATE_ADD(NOW(), INTERVAL ? DAY)
                END
            WHERE id = ?
        ");
        $user_stmt->execute([$duration, $duration, $user_id]);

        // 4. Log the successful transaction
        $trans_stmt = $pdo->prepare("
            INSERT INTO transactions (user_id, plan_id, amount_paid, payment_method, status, tx_hash) 
            VALUES (?, ?, ?, 'Paystack', 'approved', ?)
        ");
        $trans_stmt->execute([$user_id, $plan_id, $amount, $reference]);

        // 5. Mark pending payment as processed
        $update_stmt = $pdo->prepare("
            UPDATE pending_payments 
            SET status = 'processed', processed_at = NOW() 
            WHERE reference = ?
        ");
        $update_stmt->execute([$reference]);

        // 6. Clear session data
        if (isset($_SESSION['invoice_data'])) unset($_SESSION['invoice_data']);
        if (isset($_SESSION['paystack_reference'])) unset($_SESSION['paystack_reference']);

        // Commit all changes
        $pdo->commit();

        // ============================================================
        // 🔥 SEND EMAILS AFTER SUCCESSFUL PAYMENT
        // ============================================================
        // Fetch user details
        $user_stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
        $user_stmt->execute([$user_id]);
        $user = $user_stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $emailService = new EmailService($pdo);
            
            // Send VIP upgrade email
            $emailService->sendTemplateEmail('vip_upgrade', $user['email'], [
                'user_name'   => $user['full_name'],
                'expiry_date' => date('F j, Y', strtotime($expiry_date))
            ]);
            
            // Send payment confirmation
            $emailService->sendTemplateEmail('payment_confirmation', $user['email'], [
                'user_name'      => $user['full_name'],
                'amount'         => '$' . number_format($amount, 2),
                'currency'       => 'USD',
                'plan_name'      => $plan_name,
                'transaction_id' => $reference
            ]);
        }
        // ============================================================

        return ['success' => true, 'message' => 'Subscription activated successfully!'];

    } catch (Exception $e) {
        // Rollback on error
        if (isset($pdo)) $pdo->rollBack();
        return ['success' => false, 'message' => $e->getMessage()];
    }
}
?>