<?php
session_start();

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

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

$userid = $_SESSION['userid'];

// Fetch user's name for the welcome message
$sql_user = "SELECT firstname, lastname FROM users WHERE userid = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $userid);
$stmt_user->execute();
$stmt_user->bind_result($firstname, $lastname);
$stmt_user->fetch();
$stmt_user->close();

if (!isset($_GET['invoice_id'])) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'No invoice ID provided.'];
    header("Location: index.php");
    exit();
}

$invoice_id = $_GET['invoice_id'];

// Fetch invoice details
$sql_invoice = "SELECT id, userid, name, price, status, ticket_id, route FROM invoices WHERE id = ? AND userid = ?";
$stmt_invoice = $conn->prepare($sql_invoice);
$stmt_invoice->bind_param("ii", $invoice_id, $userid);
$stmt_invoice->execute();
$result_invoice = $stmt_invoice->get_result();
$invoice = $result_invoice->fetch_assoc();
$stmt_invoice->close();

if (!$invoice || $invoice['userid'] != $userid) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Invoice not found or unauthorized.'];
    header("Location: index.php");
    exit();
}

// If the invoice is already paid, redirect
if ($invoice['status'] === 'paid') {
    $_SESSION['alert_message'] = ['type' => 'info', 'message' => 'This invoice has already been paid.'];
    header("Location: index.php");
    exit();
}

// Handle payment confirmation
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['confirm_payment'])) {
    $conn->begin_transaction();

    try {
        // 1. Update invoice status to 'paid'
        $sql_update_invoice = "UPDATE invoices SET status = 'unpaid' WHERE id = ?";
        $stmt_update_invoice = $conn->prepare($sql_update_invoice);
        if ($stmt_update_invoice === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt_update_invoice->bind_param("i", $invoice_id);
        $stmt_update_invoice->execute();
        if ($stmt_update_invoice->affected_rows === 0) {
            throw new Exception("Failed to update invoice status.");
        }
        $stmt_update_invoice->close();

        // 2. Fetch ticket details (using invoice name to find original ticket)
        // This assumes invoice.name matches tickets.name exactly. A better approach
        // would be to store ticket_id in the invoice table during creation.
        $sql_ticket_details = "SELECT id, name, expire_days, occasions FROM tickets WHERE id = ?";
        $stmt_ticket_details = $conn->prepare($sql_ticket_details);
        if ($stmt_ticket_details === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt_ticket_details->bind_param("i", $invoice['ticket_id']);
        $stmt_ticket_details->execute();
        $result_ticket_details = $stmt_ticket_details->get_result();
        $ticket_details = $result_ticket_details->fetch_assoc();
        $stmt_ticket_details->close();

        if (!$ticket_details) {
            throw new Exception("Original ticket details not found for invoice.");
        }

        // 3. Insert into current_tickets
        $buydate = date('Y-m-d H:i:s');
        $expiredate = date('Y-m-d H:i:s', strtotime($buydate . ' + ' . $ticket_details['expire_days'] . ' days'));
        $opportunities = ($ticket_details['occasions'] === NULL) ? -1 : $ticket_details['occasions']; // -1 for unlimited

        $sql_insert_current_ticket = "INSERT INTO current_tickets (userid, ticketname, buydate, expiredate, opportunities) VALUES (?, ?, ?, ?, ?)";
        $stmt_insert_current_ticket = $conn->prepare($sql_insert_current_ticket);
        if ($stmt_insert_current_ticket === false) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmt_insert_current_ticket->bind_param("isssi", $userid, $ticket_details['name'], $buydate, $expiredate, $opportunities);
        $stmt_insert_current_ticket->execute();
        if ($stmt_insert_current_ticket->affected_rows === 0) {
            throw new Exception("Failed to assign ticket to user.");
        }
        $stmt_insert_current_ticket->close();

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

        $_SESSION['alert_message'] = ['type' => 'success', 'message' => 'Payment confirmed and ticket assigned!'];
        header("Location: index.php");
        exit();

    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Payment confirmation failed: ' . $e->getMessage()];
        header("Location: index.php");
        exit();
    }
}

$conn->close();

$page = 'tienda'; // Set the active page for the header
require_once '../../assets/templates/header-dashboard.php';
?>

<div class="d-none topnav d-sm-inline-block">
    <h4><?php echo $translations["welcome"]; ?> <?php echo $lastname; ?> <?php echo $firstname; ?></h4>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#logoutModal">
        <?php echo $translations["logout"]; ?>
    </button>
</div>

<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title fw-semibold">Confirm Payment for Invoice #<?php echo htmlspecialchars($invoice['id']); ?></h4>
                <p><strong>Item:</strong> <?php echo htmlspecialchars($invoice['name']); ?></p>
                <p><strong>Amount:</strong> <?php echo htmlspecialchars($invoice['price']); ?> <?php echo htmlspecialchars($currency); ?></p>
                <p><strong>Status:</strong> <?php echo htmlspecialchars($invoice['status']); ?></p>

                <form method="POST">
                    <button type="submit" name="confirm_payment" class="btn btn-success">Confirm Payment</button>
                    <a href="index.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
require_once '../../assets/templates/footer-dashboard.php';
?>