<?php
session_start();

if (!isset($_SESSION['userid'])) {
    header("Location: ../../login/");
    exit();
}

require_once '../../config.php';

$userid = $_SESSION['userid'];

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['ticket_id'])) {
    $ticket_id = $_POST['ticket_id'];

    // 1. Validate if the user already has an active ticket of the same type
    $sql_validate = "CALL validar_ticket_activo(?, ?)";
    $stmt_validate = $conn->prepare($sql_validate);
    $stmt_validate->bind_param("ii", $userid, $ticket_id);
    $stmt_validate->execute();
    $stmt_validate->bind_result($resultado);
    $stmt_validate->fetch();
    $stmt_validate->close();

    // Clear the results from the buffer for the next query
    while($conn->more_results() && $conn->next_result());

    if ($resultado == 0) {
        // If the user already has an active ticket, show an error message
        $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'You already have an active ticket of this type.'];
        header("Location: index.php");
        exit();
    }

    // Start a transaction
    $conn->begin_transaction();

    try {
        // 2. Fetch ticket details
        $sql_ticket = "SELECT id, name, price FROM tickets WHERE id = ?";
        $stmt_ticket = $conn->prepare($sql_ticket);
        if ($stmt_ticket === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt_ticket->bind_param("i", $ticket_id);
        $stmt_ticket->execute();
        $result_ticket = $stmt_ticket->get_result();
        $ticket = $result_ticket->fetch_assoc();
        $stmt_ticket->close();

        if (!$ticket) {
            throw new Exception("Ticket not found.");
        }

        // 3. Insert into invoices with status 'unpaid'
        $invoice_name = $ticket['name'];
        $invoice_price = $ticket['price'];
        $invoice_status = 'unpaid';
        $created_at = date('Y-m-d H:i:s');

        $sql_insert_invoice = "INSERT INTO invoices (userid, name, price, status, created_at, ticket_id) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt_insert_invoice = $conn->prepare($sql_insert_invoice);
        if ($stmt_insert_invoice === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt_insert_invoice->bind_param("isdssi", $userid, $invoice_name, $invoice_price, $invoice_status, $created_at, $ticket_id);
        $stmt_insert_invoice->execute();
        if ($stmt_insert_invoice->affected_rows === 0) {
            throw new Exception("Failed to create invoice.");
        }
        $invoice_id = $conn->insert_id; // Get the ID of the newly created invoice
        $stmt_insert_invoice->close();

        // Commit the transaction
        $conn->commit();

        // Redirect to payment confirmation page
        header("Location: confirm_payment.php?invoice_id=" . $invoice_id);
        exit();

    } catch (Exception $e) {
        // Rollback the transaction on error
        $conn->rollback();

        // Redirect with error message
        $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Purchase initiation failed: ' . $e->getMessage()];
        header("Location: index.php");
        exit();
    }

} else {
    // Invalid request
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Invalid request.'];
    header("Location: index.php");
    exit();
}
?>