<?php
// ZiniPay Webhook Handler
// Called automatically by ZiniPay after payment update
require_once '../config/database.php';

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

// Parse webhook payload
$invoice_id = $_GET['invoice_id'] ?? '';
$status     = strtoupper($_GET['status'] ?? '');
$val_id     = $_GET['val_id'] ?? '';

if (empty($invoice_id) || $status !== 'TRUE') {
    http_response_code(400);
    exit('Invalid payload');
}

// Verify from backend before processing
$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);
curl_close($ch);

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

if ($verify_status !== 'COMPLETED') {
    http_response_code(200);
    exit('Not completed');
}

// Check if already processed (idempotency)
$txn_id = 'ZINI-' . $invoice_id;
$stmt = $pdo->prepare("SELECT id FROM fee_payments WHERE transaction_id=? LIMIT 1");
$stmt->execute([$txn_id]);
if ($stmt->fetch()) {
    http_response_code(200);
    exit('Already processed');
}

// Extract student_id and fee_ids from metadata
$meta_raw   = $result['metadata'] ?? [];
$metadata   = is_array($meta_raw) ? $meta_raw : json_decode($meta_raw, true);
$student_id = (int)($metadata['student_id'] ?? 0);
$fee_ids    = $metadata['fee_ids'] ?? [];

if (!$student_id || empty($fee_ids)) {
    http_response_code(400);
    exit('Missing metadata');
}

try {
    $pdo->beginTransaction();
    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]);

        $pdo->prepare("INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, notes, transaction_id, created_by)
                       VALUES (?, ?, NOW(), 'zinipay', ?, ?, ?)")
            ->execute([$fee_id, $due, 'ZiniPay Webhook - Invoice: ' . $invoice_id, $txn_id, $student_id]);
    }
    $pdo->commit();
    http_response_code(200);
    echo 'OK';
} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo 'Error: ' . $e->getMessage();
}
