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

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

function h($value) {
    return htmlspecialchars((string)($value ?? ""), ENT_QUOTES, "UTF-8");
}

$customerId = (int)($_SESSION["user_id"] ?? 0);
$shopId = (int)($_POST["shop_id"] ?? $_GET["shop_id"] ?? ($_SESSION["order_shop_id"] ?? 0));

if ($customerId <= 0) {
    echo "<p>Please log in first.</p>";
    exit;
}

/*
|--------------------------------------------------------------------------
| SAVE ORDER DATA TO SESSION WHEN COMING FROM ORDER FORM
|--------------------------------------------------------------------------
*/

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $_SESSION["order_shop_id"] = $shopId;
    $_SESSION["order_due_date"] = trim($_POST["due_date"] ?? "");
    $_SESSION["order_notes"] = trim($_POST["notes"] ?? "");

    $items = [];

    if (!empty($_POST["service_type"]) && is_array($_POST["service_type"])) {
        foreach ($_POST["service_type"] as $index => $serviceType) {
            $serviceName = $_POST["service_name"][$index] ?? "";
            $size = $_POST["size"][$index] ?? "";
            $quantity = (int)($_POST["quantity"][$index] ?? 0);

            if (trim($serviceType) !== "" && trim($serviceName) !== "" && $quantity > 0) {
                $items[] = [
                    "service_type" => trim($serviceType),
                    "service_name" => trim($serviceName),
                    "size" => trim($size),
                    "quantity" => $quantity
                ];
            }
        }
    }

    $_SESSION["order_items"] = $items;
}

$orderItems = $_SESSION["order_items"] ?? [];

if ($shopId <= 0 || empty($orderItems)) {
    echo "
    <div style='padding:40px;'>
        <h3>Missing required order details.</h3>
        <p>Please go back and select a shop/service before viewing the order summary.</p>
        <a href='customer.php?page=view-shops' style='display:inline-block;padding:10px 16px;background:#111827;color:#fff;border-radius:8px;text-decoration:none;'>
            Back to Shops
        </a>
    </div>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET SHOP
|--------------------------------------------------------------------------
*/

$shopStmt = $conn->prepare("
    SELECT id, shop_name, shop_type
    FROM users
    WHERE id = ?
      AND role = 'admin'
    LIMIT 1
");
$shopStmt->bind_param("i", $shopId);
$shopStmt->execute();
$shop = $shopStmt->get_result()->fetch_assoc();

if (!$shop) {
    echo "<p>Shop not found.</p>";
    exit;
}

/*
|--------------------------------------------------------------------------
| PREPARE ORDER ITEMS + TOTALS
|--------------------------------------------------------------------------
*/

$summaryItems = [];
$totalQty = 0;
$totalPrice = 0;
$estimatedDaysMax = 0;
$sizeItems = [];

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

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

    if ($size !== "") {
    $serviceStmt = $conn->prepare("
        SELECT 
            s.id,
            s.service_name,
            s.service_type,
            COALESCE(v.price, s.price) AS price,
            s.estimated_days
        FROM services s
        LEFT JOIN service_variants v 
            ON v.service_id = s.id 
            AND v.size = ?
            AND v.is_available = 1
        WHERE s.owner_shop_id = ?
          AND s.status = 'active'
          AND LOWER(s.service_type) = LOWER(?)
          AND LOWER(s.service_name) = LOWER(?)
        LIMIT 1
    ");
    $serviceStmt->bind_param("siss", $size, $shopId, $serviceType, $serviceName);
} else {
    $serviceStmt = $conn->prepare("
        SELECT 
            id,
            service_name,
            service_type,
            price,
            estimated_days
        FROM services
        WHERE owner_shop_id = ?
          AND status = 'active'
          AND LOWER(service_type) = LOWER(?)
          AND LOWER(service_name) = LOWER(?)
        LIMIT 1
    ");
    $serviceStmt->bind_param("iss", $shopId, $serviceType, $serviceName);
}

    $serviceStmt->execute();
    $service = $serviceStmt->get_result()->fetch_assoc();

    if (!$service) {
        continue;
    }

    $unitPrice = (float)($service["price"] ?? 0);
    $itemTotal = $unitPrice * $quantity;
    $estimatedDays = (int)($service["estimated_days"] ?? 0);

    $summaryItems[] = [
        "service_id" => (int)$service["id"],
        "service_type" => $serviceType,
        "service_name" => $serviceName,
        "size" => $size,
        "quantity" => $quantity,
        "unit_price" => $unitPrice,
        "item_total" => $itemTotal,
        "estimated_days" => $estimatedDays
    ];

    if ($size !== "") {
        $sizeItems[] = [
            "service_type" => $serviceType,
            "service_name" => $serviceName,
            "size" => $size,
            "quantity" => $quantity
        ];
    }

    $totalQty += $quantity;
    $totalPrice += $itemTotal;

    if ($estimatedDays > $estimatedDaysMax) {
        $estimatedDaysMax = $estimatedDays;
    }
}

if (empty($summaryItems)) {
    echo "
    <div style='padding:40px;'>
        <h3>No valid order items found.</h3>
        <p>Please return to the order form and try again.</p>
        <a href='customer.php?page=customer-order-now&shop_id={$shopId}' style='display:inline-block;padding:10px 16px;background:#111827;color:#fff;border-radius:8px;text-decoration:none;'>
            Back to Order Form
        </a>
    </div>";
    exit;
}

$dueDate = trim($_SESSION["order_due_date"] ?? "");
$notes = trim($_SESSION["order_notes"] ?? "");
$referenceFile = $_SESSION["order_reference_file"] ?? "";

$formattedDueDate = "N/A";
if (!empty($dueDate)) {
    $timestamp = strtotime($dueDate);
    if ($timestamp) {
        $formattedDueDate = date("F j, Y", $timestamp);
    }
}
?>

<div class="container-fluid">
<div class="order-summary-page">
    <div class="order-summary-header">
        <h1>Order Summary</h1>
        <p>Review your order before confirming.</p>
    </div>

    <div class="order-summary-card">
        <div class="summary-top">
            <div>
                <h2><?php echo h($shop["shop_name"]); ?></h2>
                <p class="summary-subtitle">Please review the details below before proceeding to payment.</p>
            </div>
        </div>

        <div class="primary-summary-box">
            <div class="primary-summary-head">
                <h3>Order Items</h3>
                <div class="summary-badges">
                    <span class="summary-badge">Total Items: <?php echo (int)$totalQty; ?></span>
                    <span class="summary-badge">Due Date: <?php echo h($formattedDueDate); ?></span>
                </div>
            </div>

            <div class="simple-order-list">
                <div class="simple-order-head">
                    <span>Item</span>
                    <span>Qty</span>
                    <span>Unit Price</span>
                    <span>Total</span>
                </div>

                <?php foreach ($summaryItems as $item): ?>
                    <div class="simple-order-row">
                        <div class="item-main">
                            <strong><?php echo h($item["service_type"]); ?></strong>
                            <div class="item-sub">
                                <?php echo h($item["service_name"]); ?>
                                <?php if (!empty($item["size"])): ?>
                                    (<?php echo h($item["size"]); ?>)
                                <?php endif; ?>
                            </div>
                        </div>

                        <div><?php echo (int)$item["quantity"]; ?></div>
                        <div>₱<?php echo number_format($item["unit_price"], 2); ?></div>
                        <div>₱<?php echo number_format($item["item_total"], 2); ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="summary-total-box">
                <span>Total Amount</span>
                <strong id="mainTotalAmount">₱<?php echo number_format($totalPrice, 2); ?></strong>
            </div>
            <div class="payment-breakdown-box" id="paymentBreakdown" style="display:none;">
    
    <div class="payment-breakdown-row">
        <span>70% Downpayment</span>
        <strong>
            ₱<?php echo number_format($totalPrice * 0.70, 2); ?>
        </strong>
    </div>

    <div class="payment-breakdown-row">
        <span>Remaining Balance</span>
        <strong>
            ₱<?php echo number_format($totalPrice * 0.30, 2); ?>
        </strong>
    </div>

</div>
        </div>
        

        <div class="secondary-summary-grid">
            <?php if (!empty($sizeItems)): ?>
                <div class="secondary-card">
                    <h4>Size Check</h4>
                    <p class="size-check-note">
                        Please make sure the selected sizes are correct before proceeding to payment.
                    </p>

                    <div class="size-check-list">
                        <?php foreach ($sizeItems as $item): ?>
                            <div class="size-check-row">
                                <div>
                                    <strong><?php echo h($item["service_type"]); ?></strong>
                                    <div class="size-check-sub">
                                        <?php echo h($item["service_name"]); ?>
                                    </div>
                                </div>

                                <div class="size-check-value">
                                    <?php echo h($item["size"]); ?>
                                    <small>Qty: <?php echo (int)$item["quantity"]; ?></small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div class="secondary-card">
                <h4>Additional Details</h4>

                <div class="secondary-list">
                    <div>
                        <span>Shop Type</span>
                        <strong><?php echo h($shop["shop_type"] ?? "Not specified"); ?></strong>
                    </div>

                    <div>
                        <span>Reference File</span>
                        <strong><?php echo h($referenceFile ?: "None"); ?></strong>
                    </div>

                    <div>
                        <span>Estimated Days</span>
                        <strong><?php echo $estimatedDaysMax > 0 ? (int)$estimatedDaysMax . " day(s)" : "N/A"; ?></strong>
                    </div>
                </div>
            </div>
        </div>

        <div class="summary-notes">
            <h4>Notes / Instructions</h4>
            <p><?php echo nl2br(h($notes ?: "No notes provided.")); ?></p>
        </div>

        <form action="customer.php?page=save-final-order" method="POST">
            <input type="hidden" name="customer_id" value="<?php echo (int)$customerId; ?>">
            <input type="hidden" name="shop_id" value="<?php echo (int)$shopId; ?>">
            <input type="hidden" name="due_date" value="<?php echo h($dueDate); ?>">
            <input type="hidden" name="notes" value="<?php echo h($notes); ?>">
            <input type="hidden" name="reference_file" value="<?php echo h($referenceFile); ?>">
            <input type="hidden" name="total_quantity" value="<?php echo (int)$totalQty; ?>">
            <input type="hidden" name="total_price" value="<?php echo $totalPrice; ?>">

            <?php foreach ($summaryItems as $index => $item): ?>
                <input type="hidden" name="items[<?php echo $index; ?>][service_id]" value="<?php echo (int)$item["service_id"]; ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][service_type]" value="<?php echo h($item["service_type"]); ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][service_name]" value="<?php echo h($item["service_name"]); ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][size]" value="<?php echo h($item["size"]); ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][quantity]" value="<?php echo (int)$item["quantity"]; ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][unit_price]" value="<?php echo $item["unit_price"]; ?>">
                <input type="hidden" name="items[<?php echo $index; ?>][item_total]" value="<?php echo $item["item_total"]; ?>">
            <?php endforeach; ?>

            <?php if ($totalQty >= 50): ?>
                <div class="payment-option-box">
                    <label>
                        <input type="radio" name="payment_option" value="full" checked>
                        Pay Full Amount
                    </label>

                    <label>
                        <input type="radio" name="payment_option" value="partial">
                        Pay 70% Downpayment
                    </label>
                </div>
            <?php else: ?>
                <input type="hidden" name="payment_option" value="full">
            <?php endif; ?>

            <div class="summary-actions">
                <a href="customer.php?page=customer-order-now&shop_id=<?php echo (int)$shopId; ?>" class="btn-secondary">
                    Back
                </a>

                <button type="submit" class="btn-primary">
                    Proceed to Payment
                </button>
            </div>
        </form>
    </div>
</div>
</div>

<style>
.order-summary-page {
    width: 100%;
    max-width: 100%;
    padding: 30px 40px;
}
.order-summary-wrapper {
    width: 100%;
}
.order-summary-header h1 {
    margin-bottom: 6px;
    font-size: 36px;
    font-weight: 800;
}

.order-summary-header p {
    margin-top: 0;
    color: #555;
}

.order-summary-card {
    width: 100%;
    background: #fff;
    border-radius: 22px;
    padding: 30px;
    box-shadow: 0 4px 18px rgba(0,0,0,0.06);
}

.summary-top {
    margin-bottom: 22px;
}

.summary-top h2 {
    margin: 0 0 6px;
    font-size: 38px;
    font-weight: 800;
}

.summary-subtitle {
    margin: 0;
    color: #666;
    font-size: 15px;
}

.primary-summary-box {
    border: 1px solid #ececec;
    border-radius: 18px;
    padding: 20px;
    margin-bottom: 20px;
    background: #fcfcfc;
}

.primary-summary-head {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 16px;
}

.primary-summary-head h3 {
    margin: 0;
    font-size: 24px;
}

.summary-badges {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.summary-badge {
    background: #eef3ff;
    color: #223b67;
    padding: 8px 12px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 600;
}

.simple-order-head,
.simple-order-row {
    display: grid;
    grid-template-columns: minmax(240px, 1.8fr) 80px 130px 130px;
    gap: 14px;
    align-items: center;
}

.simple-order-head {
    padding-bottom: 10px;
    border-bottom: 1px solid #dcdcdc;
    font-weight: 700;
}

.simple-order-row {
    padding: 14px 0;
    border-bottom: 1px solid #ececec;
}

.item-main strong {
    text-transform: capitalize;
}

.item-sub {
    color: #555;
    margin-top: 4px;
    font-size: 14px;
}

.summary-total-box {
    margin-top: 18px;
    padding: 18px 20px;
    border-radius: 14px;
    background: #f3f5f8;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.summary-total-box span {
    font-size: 20px;
}

.summary-total-box strong {
    font-size: 28px;
}

.secondary-summary-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 18px;
}

.secondary-card,
.summary-notes {
    border: 1px solid #ececec;
    border-radius: 16px;
    padding: 18px;
    background: #fff;
}

.secondary-card h4,
.summary-notes h4 {
    margin: 0 0 14px;
    font-size: 18px;
}

.secondary-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.secondary-list div,
.size-check-row {
    display: flex;
    justify-content: space-between;
    gap: 14px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
}

.secondary-list div:last-child,
.size-check-row:last-child {
    border-bottom: none;
}

.secondary-list span,
.size-check-note,
.size-check-sub {
    color: #666;
}

.secondary-list strong,
.size-check-value {
    color: #222;
    text-align: right;
}

.size-check-value small {
    display: block;
    margin-top: 4px;
    font-weight: 500;
    color: #666;
}

.summary-notes {
    margin-bottom: 18px;
}

.summary-notes p {
    margin: 0;
    color: #333;
    line-height: 1.6;
}

.payment-option-box {
    margin: 18px 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.summary-actions {
    margin-top: 18px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.btn-secondary,
.btn-primary {
    text-decoration: none;
    display: inline-block;
    padding: 12px 18px;
    border-radius: 10px;
    border: none;
    cursor: pointer;
    font-weight: 600;
}

.btn-secondary {
    background: #e5e7eb;
    color: #111827;
}

.btn-primary {
    background: #111827;
    color: white;
}

.payment-breakdown-box {
    margin-top: 15px;
    padding: 18px 20px;
    border-radius: 14px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
}

.payment-breakdown-row {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #e5e7eb;
}

.payment-breakdown-row:last-child {
    border-bottom: none;
}

.payment-breakdown-row strong {
    font-size: 20px;
}

@media (max-width: 900px) {
    .primary-summary-head,
    .secondary-summary-grid {
        display: block;
    }

    .secondary-card {
        margin-bottom: 16px;
    }

    .simple-order-head,
    .simple-order-row {
        grid-template-columns: 1.4fr 70px 100px 100px;
        font-size: 14px;
    }
}

@media (max-width: 640px) {
    .simple-order-head {
        display: none;
    }

    .simple-order-row {
        grid-template-columns: 1fr;
        gap: 6px;
    }

    .secondary-list div,
    .size-check-row {
        flex-direction: column;
        align-items: flex-start;
    }

    .secondary-list strong,
    .size-check-value {
        text-align: left;
    }

    .summary-actions {
        flex-direction: column;
    }

    .btn-secondary,
    .btn-primary {
        width: 100%;
        text-align: center;
    }
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const fullAmount = <?php echo (float)$totalPrice; ?>;
    const downpayment = fullAmount * 0.70;

    const mainTotalAmount = document.getElementById("mainTotalAmount");
    const paymentBreakdown = document.getElementById("paymentBreakdown");
    const radios = document.querySelectorAll('input[name="payment_option"]');

    radios.forEach(function (radio) {
        radio.addEventListener("change", function () {
            if (this.value === "partial") {
                mainTotalAmount.textContent = "₱" + downpayment.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });

                paymentBreakdown.style.display = "block";
            } else {
                mainTotalAmount.textContent = "₱" + fullAmount.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });

                paymentBreakdown.style.display = "none";
            }
        });
    });
});
</script>