<?php
require_once("../php/db_connect.php");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION["user_id"])) {
    echo "Please log in first.";
    exit;
}

if (!isset($_GET["order_id"])) {
    echo "Invalid order.";
    exit;
}

$customer_id = (int)$_SESSION["user_id"];
$order_id = (int)$_GET["order_id"];

$paymongo_secret_key = "sk_test_BDAynWPCk7xrukS5AsKMN7x7";

$base_url = "http://localhost:8080/taiprint";

$stmt = $conn->prepare("
    SELECT 
        id,
        total_price,
        amount_paid,
        remaining_balance,
        payment_status
    FROM orders
    WHERE id = ? AND customer_id = ?
    LIMIT 1
");

$stmt->bind_param("ii", $order_id, $customer_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "Order not found.";
    exit;
}

$order = $result->fetch_assoc();

$remaining_balance = (float)$order["remaining_balance"];

if ($remaining_balance <= 0) {
    header("Location: ../html/customer.php?page=customer-payments");
    exit;
}

$amount_centavos = (int)round($remaining_balance * 100);

$data = [
    "data" => [
        "attributes" => [
            "line_items" => [
                [
                    "name" => "Remaining Balance for Order #" . $order_id,
                    "amount" => $amount_centavos,
                    "currency" => "PHP",
                    "quantity" => 1
                ]
            ],
            "payment_method_types" => [
                "gcash",
                 "qrph",
                "card",
                "paymaya"
               
            ],
            "success_url" => $base_url . "/html/payment_success.php?order_id=" . $order_id . "&payment_option=balance",
"cancel_url" => $base_url . "/html/payment_failed.php?order_id=" . $order_id,
            "description" => "Remaining balance payment for Order #" . $order_id,
            "reference_number" => "BALANCE-" . $order_id . "-" . time(),
            "metadata" => [
                "order_id" => (string)$order_id,
                "customer_id" => (string)$customer_id,
                "payment_type" => "remaining_balance"
            ]
        ]
    ]
];

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => "https://api.paymongo.com/v2/checkout_sessions",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json"
    ],
    CURLOPT_USERPWD => $paymongo_secret_key . ":"
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);

curl_close($ch);

if ($curl_error) {
    echo "cURL Error: " . $curl_error;
    exit;
}

$response_data = json_decode($response, true);

if ($http_code < 200 || $http_code >= 300) {
    echo "<h3>PayMongo Error</h3>";
    echo "<pre>";
    print_r($response_data);
    echo "</pre>";
    exit;
}

$checkout_url = $response_data["data"]["attributes"]["checkout_url"] ?? null;

if (!$checkout_url) {
    echo "Checkout URL not found.";
    exit;
}

header("Location: " . $checkout_url);
exit;