<?php

require '../includes/config.php';

/* =========================
   VALIDATE REFERENCE
========================= */
if (!isset($_GET['reference']) || empty($_GET['reference'])) {
    echo "
        <script>
            alert('Invalid payment reference.');
            window.location.href = '../billing.php';
        </script>
        ";
    exit;
}

$ref = $_GET['reference'];

/* =========================
   VERIFY WITH PAYSTACK
========================= */
$ch = curl_init("https://api.paystack.co/transaction/verify/" . urlencode($ref));
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer sk_test_7dc7e202954226e528f527a396a6ed1799e020bc"
    ],
    CURLOPT_RETURNTRANSFER => true
]);

$response = json_decode(curl_exec($ch), true);
curl_close($ch);

if (!isset($response['data']['status']) || $response['data']['status'] !== 'success') {
        echo "
        <script>
            alert('Payment Verification Failed.');
            window.location.href = '../billing.php';
        </script>
        ";
    exit;
}

/* =========================
   FETCH PAYMENT RECORD
========================= */
$stmt = $conn->prepare("
    SELECT id, company_id, subscription_id, amount, status
    FROM payments
    WHERE reference = ?
    LIMIT 1
");
$stmt->bind_param("s", $ref);
$stmt->execute();
$payment = $stmt->get_result()->fetch_assoc();

if (!$payment) {
        echo "
        <script>
            alert('Payment record not found');
            window.location.href = '../billing.php';
        </script>
        ";
    exit;
}

/* =========================
   PREVENT DOUBLE PROCESSING
========================= */
if ($payment['status'] === 'success') {
    header("Location: ../billing-success.php");
    exit;
}

/* =========================
   DETERMINE PLAN + DURATION
========================= */
$amount = (float) $payment['amount'];

if ($amount >= 50000) {
    $plan  = 'annual';
    $days  = 365;
} else {
    $plan  = 'monthly';
    $days  = 30;
}


    /* =========================
   START TRANSACTION
========================= */
$conn->begin_transaction();

try {

    $stmt = $conn->prepare("
    SELECT
        started_at,
        ends_at,
        trial_ends_at
    FROM subscriptions
    WHERE id = ?
      AND company_id = ?
    FOR UPDATE
");
$stmt->bind_param("ii", $payment['subscription_id'], $payment['company_id']);
$stmt->execute();
$sub = $stmt->get_result()->fetch_assoc();

if (!$sub) {
    throw new Exception('Subscription not found');
}


$now = new DateTime();

if (!empty($sub['trial_ends_at']) && new DateTime($sub['trial_ends_at']) > $now) {
    // Free trial still active → start after trial
    $startDate = new DateTime($sub['trial_ends_at']);

} elseif (!empty($sub['ends_at']) && new DateTime($sub['ends_at']) > $now) {
    // Active subscription → extend
    $startDate = new DateTime($sub['ends_at']);

} else {
    // Expired or new → start now
    $startDate = $now;
}

$endDate = clone $startDate;
$endDate->modify("+{$days} days");


 $stmt = $conn->prepare("
    UPDATE subscriptions
    SET
        plan = ?,
        amount = ?,
        status = 'active',

        started_at = ?,
        ends_at = ?,

        reminder_7_sent = 0,
        expired_email_sent = 0,
        trial_ends_at = NULL
    WHERE id = ?
      AND company_id = ?
");

$startedAt = $startDate->format('Y-m-d H:i:s');
$endsAt    = $endDate->format('Y-m-d H:i:s');

$stmt->bind_param(
    "sdssii",
    $plan,
    $amount,
    $startedAt,
    $endsAt,
    $payment['subscription_id'],
    $payment['company_id']
);
$stmt->execute();

    /* -------------------------
       UPDATE PAYMENT STATUS
    ------------------------- */
    $stmt = $conn->prepare("
        UPDATE payments
        SET
            status = 'success',
            paid_at = NOW()
        WHERE id = ?
    ");
    $stmt->bind_param("i", $payment['id']);
    $stmt->execute();

    /* -------------------------
       COMMIT
    ------------------------- */
    $conn->commit();

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


} catch (Throwable $e) {

    // Roll back transaction
    $conn->rollback();

    // Log real error (for developers)
    error_log('Payment processing failed: ' . $e->getMessage());

    // User-friendly message + go back
    echo "
    <script>
        alert('Payment processing failed. Please try again or contact support.');
        window.location.href = '../billing.php';
    </script>
    ";
    exit;
}
