<?php
session_start();
require_once '../config/database.php';

$cfg = require '../config/zinipay.php';

// Get invoice_id from query param (ZiniPay redirects with ?invoice_id=...)
$invoice_id = $_GET['invoice_id'] ?? $_SESSION['zinipay_invoice_id'] ?? '';
$student_id = $_SESSION['zinipay_student_id'] ?? 0;
$fee_ids    = $_SESSION['zinipay_fee_ids'] ?? [];
$amount     = (float)($_SESSION['zinipay_amount'] ?? 0);
$val_id     = $_SESSION['zinipay_val_id'] ?? '';

if (empty($invoice_id) || !$student_id || empty($fee_ids)) {
    $_SESSION['error_message'] = 'পেমেন্ট যাচাই করা সম্ভব হয়নি।';
    header('Location: my_fees.php');
    exit();
}

// Verify payment from backend (always verify, never trust redirect params alone)
$ch = curl_init($cfg['api_base'] . '/payment/verify');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode(['invoice_id' => $invoice_id]),
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'zini-api-key: ' . $cfg['api_key'],
    ],
]);
$response  = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);
$status = strtoupper($result['status'] ?? 'FAILED');

// Clear session vars
unset($_SESSION['zinipay_val_id'], $_SESSION['zinipay_fee_ids'],
      $_SESSION['zinipay_student_id'], $_SESSION['zinipay_amount'],
      $_SESSION['zinipay_invoice_id']);

if ($status !== 'COMPLETED') {
    $_SESSION['error_message'] = 'পেমেন্ট সফল হয়নি। স্ট্যাটাস: ' . $status;
    header('Location: my_fees.php');
    exit();
}

// Payment completed — update fees table
try {
    $pdo->beginTransaction();
    $total_paid = 0;
    $last_payment_id = null;

    foreach ($fee_ids as $fee_id) {
        $fee_id = (int)$fee_id;
        $stmt = $pdo->prepare("SELECT * FROM fees WHERE id=? AND student_id=?");
        $stmt->execute([$fee_id, $student_id]);
        $fee = $stmt->fetch();
        if (!$fee) continue;

        $due = (float)($fee['amount'] - $fee['paid_amount']);
        if ($due <= 0) continue;

        $new_paid   = $fee['paid_amount'] + $due;
        $new_status = ($new_paid >= $fee['amount']) ? 'paid' : 'partial';

        $pdo->prepare("UPDATE fees SET paid_amount=?, status=?, paid_date=CURDATE() WHERE id=?")
            ->execute([$new_paid, $new_status, $fee_id]);

        $txn_id = 'ZINI-' . $invoice_id;
        $stmt = $pdo->prepare("INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, notes, transaction_id, created_by)
                               VALUES (?, ?, NOW(), 'zinipay', ?, ?, ?)");
        $stmt->execute([$fee_id, $due, 'ZiniPay - Invoice: ' . $invoice_id, $txn_id, $student_id]);
        $last_payment_id = $pdo->lastInsertId();
        $total_paid += $due;
    }

    $pdo->commit();

    $_SESSION['success_message'] = '✅ পেমেন্ট সফল হয়েছে! মোট: ৳' . number_format($total_paid, 2) .
        ($last_payment_id ? ' | <a href="receipt.php?id=' . $last_payment_id . '" target="_blank">রসিদ দেখুন</a>' : '');
    header('Location: my_fees.php');

} catch (Exception $e) {
    $pdo->rollBack();
    $_SESSION['error_message'] = 'পেমেন্ট রেকর্ড করতে সমস্যা হয়েছে: ' . $e->getMessage();
    header('Location: my_fees.php');
}
exit();
