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

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

if (!isset($_SESSION["user_id"])) {
    header("Location: index.php");
    exit();
}

$shop_id = $_SESSION["user_id"];
$order_id = (int)($_GET["order_id"] ?? 0);

if ($order_id <= 0) {
    die("Invalid order.");
}

/*
|--------------------------------------------------------------------------
| GET ORDER HEADER
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT *
    FROM orders
    WHERE id = ? AND shop_id = ?
    LIMIT 1
");
$stmt->bind_param("ii", $order_id, $shop_id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();

if (!$order) {
    die("Order not found.");
}

/*
|--------------------------------------------------------------------------
| GET ALL ORDER ITEMS FOR THIS ORDER
|--------------------------------------------------------------------------
*/
$itemStmt = $conn->prepare("
    SELECT *
    FROM order_items
    WHERE order_id = ?
    ORDER BY id ASC
");
$itemStmt->bind_param("i", $order_id);
$itemStmt->execute();
$orderItems = $itemStmt->get_result();

$items = [];
while ($row = $orderItems->fetch_assoc()) {
    $items[] = $row;
}

/*
|--------------------------------------------------------------------------
| FIND PARTNER SHOPS
|--------------------------------------------------------------------------
| Match partner shops using any service_type included in this order
|--------------------------------------------------------------------------
*/
$serviceTypes = [];
foreach ($items as $item) {
    $type = strtolower(trim($item["service_type"] ?? ""));
    if ($type !== "" && !in_array($type, $serviceTypes, true)) {
        $serviceTypes[] = $type;
    }
}

$partners = [];

$partnerStmt = $conn->prepare("
    SELECT 
        id,
        shop_name,
        shop_type
    FROM users
    WHERE role = 'admin'
      AND id != ?
    ORDER BY shop_name ASC
");
$partnerStmt->bind_param("i", $shop_id);
$partnerStmt->execute();
$partnerResult = $partnerStmt->get_result();

while ($row = $partnerResult->fetch_assoc()) {
    $partners[] = $row;
}

    
    

$customerName = trim($order["customer_name"] ?? "");
$dueDate = trim($order["due_date"] ?? "");
$totalQty = 0;
foreach ($items as $item) {
    $totalQty += (int)($item["quantity"] ?? 0);
}

if ($dueDate !== "" && $dueDate !== "0000-00-00") {
    $dueDateDisplay = date("F j, Y", strtotime($dueDate));
} else {
    $dueDateDisplay = "N/A";
}
?>

<div class="outsourcing-page">
    <h1 class="outsourcing-title">Outsourcing Request Hub</h1>

    <div class="selected-order-card">
        <h2>Selected Order</h2>

        <div class="selected-order-meta">
            <div>
                <strong>Order Code</strong>
                <span><?php echo htmlspecialchars($order["order_code"] ?? "N/A"); ?></span>
            </div>
            <div>
                <strong>Customer</strong>
                <span><?php echo htmlspecialchars($customerName !== "" ? $customerName : "N/A"); ?></span>
            </div>
            <div>
                <strong>Due Date</strong>
                <span><?php echo htmlspecialchars($dueDateDisplay); ?></span>
            </div>
            <div>
                <strong>Total Quantity</strong>
                <span><?php echo htmlspecialchars((string)$totalQty); ?></span>
            </div>
        </div>

        <div class="included-items-block">
            <h3>All Order Items Included</h3>

            <?php if (!empty($items)): ?>
                <div class="included-items-table-wrap">
                    <table class="included-items-table">
                        <thead>
                            <tr>
                                <th>Service Type</th>
                                <th>Sub Type</th>
                                <th>Size</th>
                                <th>Qty</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item["service_type"] ?? "N/A"); ?></td>
                                    <td><?php echo htmlspecialchars($item["sub_type"] ?? "N/A"); ?></td>
                                    <td><?php echo htmlspecialchars(($item["size"] ?? "") !== "" ? $item["size"] : "N/A"); ?></td>
                                    <td><?php echo htmlspecialchars((string)($item["quantity"] ?? 0)); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p>No order items found.</p>
            <?php endif; ?>
        </div>
    </div>

    <h2 class="partner-title">Find Partner</h2>

    <?php if (!empty($partners)): ?>
        <div class="partner-grid">
            <?php foreach ($partners as $partner): ?>
                <div class="partner-card">
                    <div class="partner-image-box">
                        <div class="no-image">No Image</div>
                    </div>

                    <h3><?php echo htmlspecialchars($partner["shop_name"] ?? "Unknown Shop"); ?></h3>
                    <p class="partner-specialty">
                        <strong>Specialty:</strong>
                        <?php echo htmlspecialchars($partner["shop_type"] ?? $partner["type_name"] ?? "N/A"); ?>
                    </p>

                    <a
                        href="admin.php?page=submit-outsourcing-request&order_id=<?php echo (int)$order_id; ?>&target_shop_id=<?php echo (int)$partner['id']; ?>"
                        class="select-shop-btn"
                    >
                        Select Shop
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="partner-empty">
            No matching partner shops found for this order.
        </div>
    <?php endif; ?>
</div>

<style>
.outsourcing-page{
    width:100%;
    max-width:none;
}

.outsourcing-title{
    font-size:28px;
    font-weight:800;
    margin:0 0 24px;
    color:#111;
}

.selected-order-card{
    background:#fff;
    border-radius:22px;
    padding:24px;
    box-shadow:0 10px 30px rgba(0,0,0,0.08);
    margin-bottom:24px;
}

.selected-order-card h2{
    margin:0 0 18px;
    font-size:22px;
}

.selected-order-meta{
    display:grid;
    grid-template-columns:repeat(4, minmax(0, 1fr));
    gap:18px;
    margin-bottom:22px;
}

.selected-order-meta div{
    display:flex;
    flex-direction:column;
    gap:6px;
}

.selected-order-meta strong{
    font-size:15px;
    color:#111;
}

.selected-order-meta span{
    font-size:16px;
    color:#222;
    word-break:break-word;
}

.included-items-block h3{
    font-size:18px;
    margin:0 0 12px;
}

.included-items-table-wrap{
    overflow-x:auto;
}

.included-items-table{
    width:100%;
    border-collapse:collapse;
}

.included-items-table th,
.included-items-table td{
    text-align:left;
    padding:12px 10px;
    border-bottom:1px solid #e3e3e3;
}

.included-items-table th{
    font-weight:700;
    background:#f7f7f7;
}

.partner-title{
    font-size:20px;
    font-weight:800;
    margin:0 0 16px;
}

.partner-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit, minmax(220px, 240px));
    gap:20px;
}

.partner-card{
    background:#fff;
    border-radius:20px;
    padding:18px;
    box-shadow:0 10px 30px rgba(0,0,0,0.08);
}

.partner-image-box{
    width:100%;
    height:150px;
    border-radius:14px;
    background:#f2f2f2;
    display:flex;
    align-items:center;
    justify-content:center;
    margin-bottom:14px;
}

.no-image{
    color:#555;
    font-size:18px;
}

.partner-card h3{
    margin:0 0 10px;
    font-size:18px;
}

.partner-specialty{
    margin:0 0 14px;
    line-height:1.5;
}

.select-shop-btn{
    display:inline-block;
    background:#1da1f2;
    color:#fff;
    text-decoration:none;
    padding:10px 16px;
    border-radius:10px;
    font-weight:600;
}

.partner-empty{
    background:#fff;
    border-radius:16px;
    padding:18px;
    box-shadow:0 10px 30px rgba(0,0,0,0.08);
}

@media (max-width: 900px){
    .selected-order-meta{
        grid-template-columns:1fr 1fr;
    }
}

@media (max-width: 640px){
    .selected-order-meta{
        grid-template-columns:1fr;
    }
}
</style>