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

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

$paymongoSecretKey = "sk_test_BDAynWPCk7xrukS5AsKMN7x7";

$shopId = (int)($_POST['shop_id'] ?? 0);
$serviceId = (int)($_POST['service_id'] ?? 0);
$quantity = (int)($_POST['quantity'] ?? 0);
// 🔽 ADD THIS RIGHT AFTER getting $serviceId
$serviceStmt = $conn->prepare("
    SELECT service_name, service_type, price
    FROM services
    WHERE id = ?
    LIMIT 1
");
$serviceStmt->bind_param("i", $serviceId);
$serviceStmt->execute();
$service = $serviceStmt->get_result()->fetch_assoc();

$itemName = $service['service_name'] ?? '';
$serviceType = $service['service_type'] ?? '';
$unitPrice = (float)($service['price'] ?? 0);
$size = trim($_POST['size'] ?? '');
$dueDate = !empty($_POST['due_date']) ? $_POST['due_date'] : null;
$notes = trim($_POST['notes'] ?? '');
$totalPrice = (float)($_POST['total_price'] ?? 0);

if ($shopId <= 0 || $serviceId <= 0 || $quantity <= 0 || $totalPrice <= 0) {
    die("Missing payment details.");
}

/*
|--------------------------------------------------------------------------
| SAVE ORDER FIRST AS UNPAID/PENDING
|--------------------------------------------------------------------------
*/
$paymentStatus = 'pending';
$orderStatus = 'pending';
$orderCode = 'ORD-' . date('YmdHis') . '-' . rand(1000, 9999);

$customerId = $_SESSION['user_id'] ?? 0;

$userStmt = $conn->prepare("
    SELECT first_name, last_name, email, mobile_number
    FROM users
    WHERE id = ?
    LIMIT 1
");
$userStmt->bind_param("i", $customerId);
$userStmt->execute();
$user = $userStmt->get_result()->fetch_assoc();

$customerName = ($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '');
$customerEmail = $user['email'] ?? '';
$customerMobile = $user['mobile_number'] ?? '';

$stmt = $conn->prepare("
    INSERT INTO orders (
        order_code,
        customer_id,
        customer_name,
        customer_email,
        customer_mobile,
        shop_id,
        service_id,
        service_type,
        item_name,
        quantity,
        size,
        unit_price,
        total_price,
        due_date,
        status,
        payment_status,
        notes
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$stmt->bind_param(
    "sisssiissisddssss",
    $orderCode,
    $customerId,
    $customerName,
    $customerEmail,
    $customerMobile,
    $shopId,
    $serviceId,
    $serviceType,
    $itemName,
    $quantity,
    $size,
    $unitPrice,
    $totalPrice,
    $dueDate,
    $orderStatus,
    $paymentStatus,
    $notes
);

if (!$stmt->execute()) {
    die("Order save failed: " . $stmt->error);
}

$orderId = $stmt->insert_id;

/*
|--------------------------------------------------------------------------
| CREATE PAYMONGO CHECKOUT SESSION
|--------------------------------------------------------------------------
*/



$sessionReference = "ORDER-" . $orderId . "-" . time();
$baseUrl = "http://localhost:8080/taiprint/html";

// PayMongo amount must be in centavos
// Example: 100 pesos = 10000
$amountInCentavos = (int) round($totalPrice * 100);

$data = [
    "data" => [
        "attributes" => [
            "send_email_receipt" => false,
            "show_description" => true,
            "show_line_items" => true,

            "description" => "Payment for Order " . $orderCode,
            "reference_number" => $sessionReference,

            // Since your dashboard shows QRPh is active, use qrph first.
            // Add "card" and "gcash" only if activated in PayMongo.
            "payment_method_types" => ["qrph"],

            "line_items" => [
                [
                    "name" => $itemName ?: "Order Payment",
                    "description" => $serviceType ?: "Service Payment",
                    "amount" => $amountInCentavos,
                    "currency" => "PHP",
                    "quantity" => 1
                ]
            ],

            "billing" => [
                "name" => trim($customerName),
                "email" => $customerEmail,
                "phone" => $customerMobile
            ],

            "success_url" => $baseUrl . "/customer.php?page=payment_success&order_id=" . $orderId,
            "cancel_url" => $baseUrl . "/customer.php?page=payment_failed&order_id=" . $orderId,

            "metadata" => [
                "order_id" => (string) $orderId,
                "order_code" => (string) $orderCode,
                "customer_id" => (string) $customerId
            ]
        ]
    ]
];

$curl = curl_init();

curl_setopt_array($curl, [
    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 => $paymongoSecretKey . ":",
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if (curl_errno($curl)) {
    die("cURL Error: " . curl_error($curl));
}

curl_close($curl);

$result = json_decode($response, true);

if (!empty($result["data"]["attributes"]["checkout_url"])) {
    $checkoutSessionId = $result["data"]["id"];

    // Optional: save checkout session ID if your orders table has this column
    // $updateStmt = $conn->prepare("UPDATE orders SET payment_reference = ? WHERE id = ?");
    // $updateStmt->bind_param("si", $checkoutSessionId, $orderId);
    // $updateStmt->execute();

    header("Location: " . $result["data"]["attributes"]["checkout_url"]);
    exit;
}

echo "<pre>";
echo "HTTP Code: " . $httpCode . "\n";
print_r($result);
echo "</pre>";
exit;