<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION["user_id"])) {
    die("Not logged in.");
}

$customer_id = (int)$_SESSION["user_id"];
$shop_id = (int)($_POST["shop_id"] ?? 0);
$orderItems = $_SESSION["order_items"] ?? [];

if ($shop_id <= 0 || empty($orderItems)) {
    die("No order items to save.");
}

/*
|--------------------------------------------------------------------------
| CUSTOMER INFO
|--------------------------------------------------------------------------
*/
$first_name = trim($_SESSION["first_name"] ?? "");
$last_name = trim($_SESSION["last_name"] ?? "");
$customer_name = trim($first_name . " " . $last_name);
$customer_email = trim($_SESSION["email"] ?? "");
$customer_mobile = trim($_SESSION["mobile_number"] ?? "");

/*
|--------------------------------------------------------------------------
| OPTIONAL: normalize PH mobile to +63 format
|--------------------------------------------------------------------------
*/
if ($customer_mobile !== '') {
    if (preg_match('/^09\d{9}$/', $customer_mobile)) {
        $customer_mobile = '+63' . substr($customer_mobile, 1);
    } elseif (preg_match('/^9\d{9}$/', $customer_mobile)) {
        $customer_mobile = '+63' . $customer_mobile;
    }
}

/*
|--------------------------------------------------------------------------
| ORDER-LEVEL FIELDS FROM SUMMARY FORM
|--------------------------------------------------------------------------
*/
$due_date = trim($_POST["due_date"] ?? "");
$notes = trim($_POST["notes"] ?? "");
$reference_file = trim($_POST["reference_file"] ?? "");
$total_quantity = (int)($_POST["total_quantity"] ?? 0);
$total_price = (float)($_POST["total_price"] ?? 0);
$payment_option = trim($_POST["payment_option"] ?? "full");


if ($payment_option === 'partial') {
    $amount_to_pay = $total_price * 0.70;
    $remaining_balance = $total_price * 0.30;
} else {
    $amount_to_pay = $total_price;
    $remaining_balance = 0;
}

if ($total_quantity <= 0 || $total_price <= 0) {
    die("Missing payment details.");
}

/*
|--------------------------------------------------------------------------
| DEFAULTS
|--------------------------------------------------------------------------
*/
$order_code = "ORD-" . time();
$status = "pending";
$payment_status = "pending";
$order_date = date("Y-m-d");

/*
|--------------------------------------------------------------------------
| FLATTEN FIRST ITEM FOR ORDERS TABLE DISPLAY
|--------------------------------------------------------------------------
*/
$firstItem = $orderItems[0] ?? [];

$service_type = trim($firstItem["service_type"] ?? "");
$item_name = trim($firstItem["service_name"] ?? "");
$size = trim($firstItem["size"] ?? "");

/*
|--------------------------------------------------------------------------
| COMPUTE ESTIMATED DELIVERY + GET FIRST SERVICE ID/PRICE
|--------------------------------------------------------------------------
*/
$max_estimated_days = 0;
$service_id_for_order = null;
$unit_price_for_order = 0.00;

foreach ($orderItems as $index => $item) {
    $serviceType = trim($item["service_type"] ?? "");
    $serviceName = trim($item["service_name"] ?? "");

    if ($serviceType === "" || $serviceName === "") {
        continue;
    }

    $svcStmt = $conn->prepare("
        SELECT id, price, estimated_days
        FROM services
        WHERE owner_shop_id = ?
          AND service_type = ?
          AND service_name = ?
          AND status = 'active'
        LIMIT 1
    ");

    if (!$svcStmt) {
        throw new Exception("Prepare failed (services): " . $conn->error);
    }

    $svcStmt->bind_param("iss", $shop_id, $serviceType, $serviceName);
    $svcStmt->execute();
    $svc = $svcStmt->get_result()->fetch_assoc();

    if ($svc) {
        $estimated_days = (int)($svc["estimated_days"] ?? 0);
        if ($estimated_days > $max_estimated_days) {
            $max_estimated_days = $estimated_days;
        }

        if ($index === 0) {
            $service_id_for_order = (int)$svc["id"];
            $unit_price_for_order = (float)($svc["price"] ?? 0);
        }
    }
}

$estimated_delivery = null;
if ($max_estimated_days > 0) {
    $estimated_delivery = date("Y-m-d", strtotime("+{$max_estimated_days} days"));
}

/*
|--------------------------------------------------------------------------
| SAVE ORDER + ITEMS
|--------------------------------------------------------------------------
*/
$conn->begin_transaction();

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

    if (!$stmt) {
        throw new Exception("Prepare failed (orders): " . $conn->error);
    }

    $stmt->bind_param(
        "siiisssssisddsssssss",
        $order_code,
        $customer_id,
        $shop_id,
        $service_id_for_order,
        $customer_name,
        $customer_email,
        $customer_mobile,
        $service_type,
        $item_name,
        $total_quantity,
        $size,
        $unit_price_for_order,
        $total_price,
        $order_date,
        $due_date,
        $estimated_delivery,
        $status,
        $payment_status,
        $notes,
        $reference_file
    );

    if (!$stmt->execute()) {
        throw new Exception("Execute failed (orders): " . $stmt->error);
    }

    $order_id = $conn->insert_id;

    foreach ($orderItems as $item) {
        $serviceType = trim($item["service_type"] ?? "");
        $subType = trim($item["service_name"] ?? "");
        $itemSize = trim($item["size"] ?? "");
        $itemQty = (int)($item["quantity"] ?? 0);

        if ($serviceType === "" || $subType === "" || $itemQty <= 0) {
            continue;
        }

        $stmtItem = $conn->prepare("
            INSERT INTO order_items (order_id, service_type, sub_type, size, quantity)
            VALUES (?, ?, ?, ?, ?)
        ");

        if (!$stmtItem) {
            throw new Exception("Prepare failed (order_items): " . $conn->error);
        }

        $stmtItem->bind_param(
            "isssi",
            $order_id,
            $serviceType,
            $subType,
            $itemSize,
            $itemQty
        );

        if (!$stmtItem->execute()) {
            throw new Exception("Execute failed (order_items): " . $stmtItem->error);
        }
    }

    $conn->commit();

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

$paymongoSecretKey = trim("sk_test_BDAynWPCk7xrukS5AsKMN7x7");
$base_url = "http://localhost:8080/taiprint/html";

$sessionReference = "ORDER-" . $order_id . "-" . time();

$success_url = $base_url . "/payment_success.php?order_id=" . $order_id
    . "&payment_option=" . urlencode($payment_option)
    . "&amount_paid=" . urlencode($amount_to_pay)
    . "&remaining_balance=" . urlencode($remaining_balance)
    . "&ref=" . urlencode($sessionReference);
$cancel_url = $base_url . "/payment_failed.php?order_id=" . $order_id;

$payment_option = $_POST['payment_option'] ?? 'full';

if ($payment_option === 'partial') {
    $amount_to_pay = $total_price * 0.70;
    $remaining_balance = $total_price * 0.30;
} else {
    $amount_to_pay = $total_price;
    $remaining_balance = 0;
}

$amountInCentavos = (int) round($amount_to_pay * 100);

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

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

           "payment_method_types" => ["card", "gcash", "qrph"],

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

            "billing" => [
                "name" => $customer_name,
                "email" => $customer_email,
                "phone" => $customer_mobile
            ],

            "success_url" => $success_url,
            "cancel_url" => $cancel_url,

            "metadata" => [
                "order_id" => (string)$order_id,
                "shop_id" => (string)$shop_id,
                "customer_id" => (string)$customer_id,
                "payment_option" => (string)$payment_option
            ]
        ]
    ]
];

$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",
        "Accept: application/json"
    ],
    CURLOPT_USERPWD => $paymongoSecretKey . ":",
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);

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

if (curl_errno($curl)) {
    throw new Exception("cURL Error: " . curl_error($curl));
}

curl_close($curl);

$result = json_decode($response, true);

if (!empty($result["data"]["attributes"]["checkout_url"])) {
    unset($_SESSION["order_items"]);
    unset($_SESSION["order_due_date"]);
    unset($_SESSION["order_notes"]);
    unset($_SESSION["order_reference_file"]);

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

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

} catch (Exception $e) {
    $conn->rollback();
    die("Order save failed: " . $e->getMessage());
}
?>