<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['local_order_id']);

$pdo = getDbConnection();

$txnStmt = $pdo->prepare(
    'SELECT * FROM payment_transactions WHERE order_id = :order_id AND user_email = :email LIMIT 1'
);
$txnStmt->execute([':order_id' => clean_str($input['local_order_id']), ':email' => $authUser['email']]);
$txn = $txnStmt->fetch();

if (!$txn) {
    send_error('Transaction not found.', 404);
}
if (in_array($txn['status'], ['SUCCESS', 'VERIFIED'], true)) {
    send_success(null, 'Payment already verified.');
}

// ---- Razorpay: verify HMAC signature, auto-activate ----
if ($txn['gateway'] === 'RAZORPAY') {
    require_fields($input, ['razorpay_order_id', 'razorpay_payment_id', 'razorpay_signature']);

    $gwStmt = $pdo->prepare("SELECT key_secret FROM payment_gateways WHERE gateway_name = 'RAZORPAY'");
    $gwStmt->execute();
    $keySecret = $gwStmt->fetchColumn();

    $expectedSignature = hash_hmac(
        'sha256',
        $input['razorpay_order_id'] . '|' . $input['razorpay_payment_id'],
        $keySecret
    );

    if (!hash_equals($expectedSignature, $input['razorpay_signature'])) {
        $fail = $pdo->prepare("UPDATE payment_transactions SET status = 'FAILED' WHERE id = :id");
        $fail->execute([':id' => $txn['id']]);
        send_error('Payment signature verification failed.', 400);
    }

    $pdo->beginTransaction();
    try {
        $upd = $pdo->prepare(
            "UPDATE payment_transactions SET status = 'SUCCESS', payment_id = :payment_id,
             signature = :signature, verified_at = NOW() WHERE id = :id"
        );
        $upd->execute([
            ':payment_id' => $input['razorpay_payment_id'],
            ':signature'  => $input['razorpay_signature'],
            ':id'         => $txn['id'],
        ]);

        $extend = $pdo->prepare(
            'UPDATE users SET validity_days = validity_days + :days, activated_at = NOW() WHERE email = :email'
        );
        $extend->execute([':days' => (int) $txn['validity_days_added'], ':email' => $authUser['email']]);

        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        send_error('Failed to activate plan after payment. Contact support with your order ID: ' . $txn['order_id'], 500);
    }

    send_success(null, 'Payment verified. Your plan is now active.');
}

// ---- Manual UPI: record UTR, wait for admin approval ----
if ($txn['gateway'] === 'MANUAL_UPI') {
    require_fields($input, ['utr_number']);

    $utr = clean_str($input['utr_number']);
    if (strlen($utr) < 6) {
        send_error('Enter a valid UTR / reference number.', 422);
    }

    $upd = $pdo->prepare('UPDATE payment_transactions SET utr_number = :utr WHERE id = :id');
    $upd->execute([':utr' => $utr, ':id' => $txn['id']]);

    send_success(null, 'UTR submitted. Your payment will be verified by our team shortly.');
}

// ---- PhonePe: mark pending for manual/webhook verification ----
if ($txn['gateway'] === 'PHONEPE') {
    send_success(null, 'Payment submitted. It will be confirmed automatically once PhonePe verification completes.');
}

send_error('Unsupported gateway for verification.', 500);
