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

require_once "../php/db_connect.php";

$current_user_id = isset($_SESSION["user_id"]) ? (int)$_SESSION["user_id"] : 0;
$order_id = isset($_GET["order_id"]) ? (int)$_GET["order_id"] : 0;
$target_shop_id = isset($_GET["target_shop_id"]) ? (int)$_GET["target_shop_id"] : 0;

if ($current_user_id <= 0) {
    echo "<script>
        alert('Unauthorized access.');
        window.location.href='index.php';
    </script>";
    exit;
}

if ($order_id <= 0 || $target_shop_id <= 0) {
    echo "<script>
        alert('Invalid order or target shop.');
        window.location.href='admin.php?page=orders';
    </script>";
    exit;
}

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

/*
|--------------------------------------------------------------------------
| LOAD ORDER HEADER
|--------------------------------------------------------------------------
*/
$stmtOrder = $conn->prepare("
    SELECT id, order_code, shop_id, due_date, notes, design_file, status, customer_name
    FROM orders
    WHERE id = ? AND shop_id = ?
    LIMIT 1
");

if (!$stmtOrder) {
    die("Order query prepare failed: " . $conn->error);
}

$stmtOrder->bind_param("ii", $order_id, $current_user_id);
$stmtOrder->execute();
$orderResult = $stmtOrder->get_result();

if (!$orderResult || $orderResult->num_rows === 0) {
    echo "<script>
        alert('Order not found or not owned by your shop.');
        window.location.href='admin.php?page=orders';
    </script>";
    exit;
}

$order = $orderResult->fetch_assoc();

/*
|--------------------------------------------------------------------------
| LOAD ORDER ITEMS
|--------------------------------------------------------------------------
*/
$stmtItems = $conn->prepare("
    SELECT id, service_type, sub_type, size, quantity
    FROM order_items
    WHERE order_id = ?
    ORDER BY id ASC
");

if (!$stmtItems) {
    die("Items query prepare failed: " . $conn->error);
}

$stmtItems->bind_param("i", $order_id);
$stmtItems->execute();
$itemsResult = $stmtItems->get_result();

$orderItems = [];
$totalQty = 0;

while ($row = $itemsResult->fetch_assoc()) {
    $orderItems[] = $row;
    $totalQty += (int)($row["quantity"] ?? 0);
}

/*
|--------------------------------------------------------------------------
| LOAD TARGET SHOP
| Do not make status too strict here.
|--------------------------------------------------------------------------
*/
$stmtShop = $conn->prepare("
    SELECT id, shop_name, main_services, shop_image
    FROM users
    WHERE id = ?
      AND role = 'admin'
    LIMIT 1
");

if (!$stmtShop) {
    die("Shop query prepare failed: " . $conn->error);
}

$stmtShop->bind_param("i", $target_shop_id);
$stmtShop->execute();
$shopResult = $stmtShop->get_result();

if (!$shopResult || $shopResult->num_rows === 0) {
    echo "<script>
        alert('Target shop not found.');
        window.location.href='admin.php?page=outsourcing-hub&order_id={$order_id}';
    </script>";
    exit;
}

$target_shop = $shopResult->fetch_assoc();

$shopImage = !empty($target_shop["shop_image"])
    ? "../uploads/" . h($target_shop["shop_image"])
    : "";
?>

<div class="container-fluid px-0 outsourcing-submit-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Submit Outsourcing Request</h1>
            <p class="text-muted mb-0">
                Review the order details before sending the request to your partner shop.
            </p>
        </div>

        <a href="admin.php?page=outsourcing-hub&order_id=<?php echo (int)$order_id; ?>" class="btn btn-light border rounded-pill px-4">
            Back
        </a>
    </div>

    <div class="row g-4">

        <div class="col-lg-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4">

                    <h5 class="fw-bold mb-3">Selected Partner Shop</h5>

                    <div class="partner-image mb-3">
                        <?php if (!empty($shopImage)): ?>
                            <img src="<?php echo $shopImage; ?>" alt="Shop Image">
                        <?php else: ?>
                            <div class="no-image-box">
                                <i class="fa-solid fa-shop"></i>
                                <span>No Image</span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <h4 class="fw-bold mb-1">
                        <?php echo h($target_shop["shop_name"]); ?>
                    </h4>

                    <p class="text-muted mb-0">
                        <strong>Specialty:</strong>
                        <?php echo h($target_shop["main_services"] ?? "N/A"); ?>
                    </p>

                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card border-0 shadow-sm rounded-4 mb-4">
                <div class="card-body p-4">

                    <h5 class="fw-bold mb-3">Order Details Shared to Partner</h5>

                    <div class="row g-3 mb-4">
                        <div class="col-md-3">
                            <div class="detail-box">
                                <small>Order Code</small>
                                <strong><?php echo h($order["order_code"]); ?></strong>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="detail-box">
                                <small>Customer</small>
                                <strong><?php echo h($order["customer_name"] ?: "N/A"); ?></strong>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="detail-box">
                                <small>Due Date</small>
                                <strong><?php echo !empty($order["due_date"]) ? h($order["due_date"]) : "N/A"; ?></strong>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="detail-box">
                                <small>Total Quantity</small>
                                <strong><?php echo (int)$totalQty; ?></strong>
                            </div>
                        </div>
                    </div>

                    <h6 class="fw-bold mb-2">All Order Items Included</h6>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0 outsourcing-table">
                            <thead>
                                <tr>
                                    <th>Service Type</th>
                                    <th>Sub Type</th>
                                    <th>Size</th>
                                    <th>Qty</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php if (!empty($orderItems)): ?>
                                    <?php foreach ($orderItems as $item): ?>
                                        <tr>
                                            <td><?php echo h($item["service_type"] ?: "N/A"); ?></td>
                                            <td><?php echo h($item["sub_type"] ?: "N/A"); ?></td>
                                            <td><?php echo h($item["size"] ?: "N/A"); ?></td>
                                            <td><?php echo (int)($item["quantity"] ?? 0); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-4">
                                            No order items found.
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if (!empty($order["design_file"])): ?>
                        <div class="mt-3">
                            <strong>Current Design File:</strong><br>
                            <a href="../uploads/orders/<?php echo h($order["design_file"]); ?>" target="_blank">
                                View current design file
                            </a>
                        </div>
                    <?php endif; ?>

                </div>
            </div>

            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-body p-4">

                    <h5 class="fw-bold mb-3">Request Instructions</h5>

                    <form action="save_outsourcing_request.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="order_id" value="<?php echo (int)$order["id"]; ?>">
                        <input type="hidden" name="target_shop_id" value="<?php echo (int)$target_shop["id"]; ?>">

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Required Date</label>
                            <input
                                type="date"
                                name="required_date"
                                class="form-control"
                                value="<?php echo h($order["due_date"] ?? ""); ?>"
                            >
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Additional Instructions / Notes</label>
                            <textarea
                                name="request_message"
                                rows="5"
                                class="form-control"
                                placeholder="Add production instructions, materials, color, print method, etc."
                            ><?php echo h($order["notes"] ?? ""); ?></textarea>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-semibold">Attach Design File</label>
                            <input
                                type="file"
                                name="attachment_file"
                                class="form-control"
                                accept=".jpg,.jpeg,.png,.pdf,.ai,.psd,.cdr"
                            >
                            <small class="text-muted">
                                Optional. Accepted files: JPG, PNG, PDF, AI, PSD, CDR.
                            </small>
                        </div>

                        <div class="d-flex justify-content-end gap-2">
                            <a href="admin.php?page=outsourcing-hub&order_id=<?php echo (int)$order_id; ?>" class="btn btn-light border px-4">
                                Cancel
                            </a>

                            <button type="submit" class="btn btn-primary px-4">
                                Send Outsourcing Request
                            </button>
                        </div>
                    </form>

                </div>
            </div>

        </div>

    </div>

</div>

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

.partner-image {
    width: 100%;
    height: 180px;
    border-radius: 18px;
    overflow: hidden;
    background: #f3f4f6;
}

.partner-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.no-image-box {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
    justify-content: center;
    color: #6b7280;
}

.no-image-box i {
    font-size: 34px;
}

.detail-box {
    background: #f8fafc;
    border-radius: 14px;
    padding: 14px;
    height: 100%;
}

.detail-box small {
    display: block;
    color: #6b7280;
    margin-bottom: 4px;
}

.detail-box strong {
    color: #111827;
}

.outsourcing-table thead th {
    background: #f8fafc;
    font-size: 14px;
    font-weight: 700;
    padding: 14px;
    white-space: nowrap;
}

.outsourcing-table tbody td {
    padding: 14px;
    font-size: 14px;
}

.form-control {
    border-radius: 10px;
    padding: 10px 12px;
}

@media (max-width: 768px) {
    .partner-image {
        height: 150px;
    }
}
</style>