<?php
session_start();
require '../includes/config.php';
require_once 'helpers.php'; // jsAlert()

/* =========================
   SESSION VALIDATION
========================= */
if (
    !isset(
        $_SESSION['company_id'],
        $_SESSION['email'],
        $_SESSION['role']
    )
) {
         jsAlert(
        'Oops! You are not Signed in',
        'Login or Create an account to purchase a plan',
        'error',
        '../sign-in.php'
    );
    exit;
}

/* =========================
   ADMIN CHECK
========================= */
if ($_SESSION['role'] !== 'admin') {
     jsAlert(
        'Oops! You are not an ADMIN',
        'Only Admin can purchase a plan, contact your Admin',
        'error',
        '../dashboard.php'
    );
    exit;
}

$company_id = (int) $_SESSION['company_id'];
$email      = $_SESSION['email'];
$plan       = $_POST['plan'] ?? 'monthly';

/* =========================
   PLAN & AMOUNT
========================= */
$amount   = ($plan === 'annual') ? 50000 : 5000;
$currency = 'NGN';

/* =========================
   CHECK SUBSCRIPTION STATUS
========================= */
$stmt = $conn->prepare("
    SELECT id, status
    FROM subscriptions
    WHERE company_id = ?
    ORDER BY id DESC
    LIMIT 1
");
$stmt->bind_param("i", $company_id);
$stmt->execute();
$subscription = $stmt->get_result()->fetch_assoc();

/* =========================
   ENSURE SUBSCRIPTION EXISTS
========================= */
if (!$subscription) {
    $stmt = $conn->prepare("
        INSERT INTO subscriptions (company_id, plan, status, created_at)
        VALUES (?, ?, 'pending', NOW())
    ");
    $stmt->bind_param("is", $company_id, $plan);
    $stmt->execute();

    $subscription_id = $conn->insert_id;
} else {
    $subscription_id = (int) $subscription['id'];
}

/* =========================
   CREATE PAYMENT (PENDING)
========================= */
$reference = uniqid("FIN_");

$stmt = $conn->prepare("
    INSERT INTO payments (
        company_id,
        subscription_id,
        amount,
        currency,
        gateway,
        status,
        reference,
        created_at
    ) VALUES (?, ?, ?, ?, 'paystack', 'pending', ?, NOW())
");

$stmt->bind_param(
    "iisss",
    $company_id,
    $subscription_id,
    $amount,
    $currency,
    $reference
);
$stmt->execute();

/* =========================
   INIT PAYSTACK
========================= */
$data = [
    "email"        => $email,
    "amount"       => $amount * 100,
    "reference"    => $reference,
    "callback_url" => "http://localhost/finvoicer/invoice360/endpoint/paystack-callback.php"
];

$ch = curl_init("https://api.paystack.co/transaction/initialize");
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer sk_test_7dc7e202954226e528f527a396a6ed1799e020bc",
        "Content-Type: application/json"
    ],
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($data),
    CURLOPT_RETURNTRANSFER => true
]);

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

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

/* =========================
   REDIRECT USER
========================= */
header("Location: " . $response['data']['authorization_url']);
exit;
