<?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;
$request_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message = $_GET['message'] ?? "";

if ($current_user_id <= 0) {
    die("Unauthorized access.");
}

if ($request_id <= 0) {
    die("Invalid request.");
}

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

function startsWithText($text, $prefix) {
    return substr($text, 0, strlen($prefix)) === $prefix;
}

function formatDateTime($date) {
    if (empty($date)) {
        return "N/A";
    }

    return date("M d, Y h:i A", strtotime($date));
}

function formatDateOnly($date) {
    if (empty($date) || $date === "0000-00-00") {
        return "N/A";
    }

    return date("M d, Y", strtotime($date));
}

function statusBadgeClass($status) {
    $status = strtolower($status ?? "");

    if ($status === "sent" || $status === "pending") {
        return "bg-warning-subtle text-warning-emphasis border border-warning-subtle";
    }

    if ($status === "accepted") {
        return "bg-success-subtle text-success border border-success-subtle";
    }

    if ($status === "responded") {
        return "bg-info-subtle text-info border border-info-subtle";
    }

    if ($status === "held") {
        return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    }

    if ($status === "declined" || $status === "rejected") {
        return "bg-danger-subtle text-danger border border-danger-subtle";
    }

    return "bg-light text-dark border";
}

function fileLink($file) {
    if (empty($file)) {
        return "";
    }

    if (
        startsWithText($file, "http") ||
        startsWithText($file, "../") ||
        startsWithText($file, "uploads/")
    ) {
        return $file;
    }

    return "../uploads/outsourcing/" . basename($file);
}

/*
|--------------------------------------------------------------------------
| GET REQUEST DETAILS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        r.id,
        r.request_code,
        r.order_id,
        r.requester_shop_id,
        r.target_shop_id,
        r.request_message,
        r.attachment_file,
        r.required_date,
        r.status AS requester_decision,
        r.created_at,
        r.reviewed_at,

        o.order_code,
        o.service_type,
        o.item_name,
        o.quantity,
        o.size,
        o.due_date,
        o.customer_name,
        o.payment_status,

        target_shop.shop_name AS target_shop_name,

        resp.id AS response_id,
        resp.response_status,
        resp.quoted_price,
        resp.estimated_days,
        resp.remarks,
        resp.submitted_at
    FROM outsourcing_requests r
    LEFT JOIN orders o 
        ON r.order_id = o.id
    LEFT JOIN users target_shop 
        ON r.target_shop_id = target_shop.id
    LEFT JOIN outsourcing_responses resp 
        ON resp.outsourcing_request_id = r.id
    WHERE r.id = ?
      AND r.requester_shop_id = ?
    LIMIT 1
");

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param("ii", $request_id, $current_user_id);
$stmt->execute();
$res = $stmt->get_result();

if (!$res || $res->num_rows === 0) {
    die("Request not found.");
}

$data = $res->fetch_assoc();

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

$orderItems = [];

if ($itemStmt) {
    $order_id = (int)$data["order_id"];
    $itemStmt->bind_param("i", $order_id);
    $itemStmt->execute();
    $itemResult = $itemStmt->get_result();

    while ($item = $itemResult->fetch_assoc()) {
        $orderItems[] = $item;
    }
}

$requestDecision = strtolower($data['requester_decision'] ?? "pending");
$requestStatus = strtoupper($requestDecision ?: "PENDING");

$responseStatusRaw = strtolower($data['response_status'] ?? "");
$responseStatus = !empty($responseStatusRaw) ? strtoupper($responseStatusRaw) : "PENDING";

$hasResponse = !empty($data["response_id"]);
$attachmentUrl = fileLink($data['attachment_file'] ?? "");

/*
|--------------------------------------------------------------------------
| SHOW DECISION PANEL
| Show only if partner responded and requester has not finalized yet.
|--------------------------------------------------------------------------
*/
$canDecide = $hasResponse
    && !in_array($requestDecision, ["accepted", "declined"])
    && $responseStatusRaw !== "declined";
?>

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

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Outsourcing Request Details</h1>
            <p class="text-muted mb-0">
                Review the request, order information, instructions, and partner response.
            </p>
        </div>

        <a href="admin.php?page=outsourcing-requests" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-arrow-left me-1"></i> Back
        </a>
    </div>

    <?php if ($message === "held"): ?>
        <div class="alert alert-warning rounded-3">
            Request has been put on hold.
        </div>
    <?php elseif ($message === "declined"): ?>
        <div class="alert alert-danger rounded-3">
            Request has been declined.
        </div>
    <?php endif; ?>

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

            <div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3">
                <div>
                    <h4 class="fw-bold mb-1">Request Info</h4>
                    <p class="text-muted mb-0">Main details of the outsourcing request.</p>
                </div>

                <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($requestDecision); ?>">
                    <?php echo h($requestStatus); ?>
                </span>
            </div>

            <div class="row g-3">
                <div class="col-md-3">
                    <div class="info-box">
                        <small>Request Code</small>
                        <strong><?php echo h($data['request_code']); ?></strong>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box">
                        <small>Target Shop</small>
                        <strong><?php echo h($data['target_shop_name'] ?: "N/A"); ?></strong>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box">
                        <small>Date Sent</small>
                        <strong><?php echo h(formatDateTime($data['created_at'])); ?></strong>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="info-box">
                        <small>Required Date</small>
                        <strong><?php echo h(formatDateOnly($data['required_date'])); ?></strong>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <div class="row g-4">

        <div class="col-lg-7">

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

                    <h4 class="fw-bold mb-3">Order Details</h4>

                    <div class="row g-3 mb-3">
                        <div class="col-md-4">
                            <div class="info-box">
                                <small>Order Code</small>
                                <strong><?php echo h($data['order_code'] ?: "N/A"); ?></strong>
                            </div>
                        </div>

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

                        <div class="col-md-4">
                            <div class="info-box">
                                <small>Due Date</small>
                                <strong><?php echo h(formatDateOnly($data['due_date'])); ?></strong>
                            </div>
                        </div>
                    </div>

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

                    <div class="table-responsive">
                        <table class="table table-hover align-middle details-table mb-0">
                            <thead>
                                <tr>
                                    <th>Service Type</th>
                                    <th>Sub Type / Item</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><?php echo h($data["service_type"] ?: "N/A"); ?></td>
                                        <td><?php echo h($data["item_name"] ?: "N/A"); ?></td>
                                        <td><?php echo h($data["size"] ?: "N/A"); ?></td>
                                        <td><?php echo (int)($data["quantity"] ?? 0); ?></td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>

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

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

                    <div class="instruction-box mb-3">
                        <?php if (!empty($data['request_message'])): ?>
                            <?php echo nl2br(h($data['request_message'])); ?>
                        <?php else: ?>
                            <span class="text-muted">No instructions provided.</span>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($attachmentUrl)): ?>
                        <a href="<?php echo h($attachmentUrl); ?>" target="_blank" class="btn btn-outline-primary rounded-pill px-4">
                            <i class="fa-solid fa-paperclip me-1"></i> View Attachment
                        </a>
                    <?php else: ?>
                        <p class="text-muted mb-0">
                            <i class="fa-solid fa-paperclip me-1"></i> No attachment uploaded.
                        </p>
                    <?php endif; ?>

                </div>
            </div>

        </div>

        <div class="col-lg-5">

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

                    <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                        <div>
                            <h4 class="fw-bold mb-1">Partner Response</h4>
                            <p class="text-muted mb-0">Response from the selected partner shop.</p>
                        </div>

                        <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($responseStatusRaw); ?>">
                            <?php echo h($responseStatus); ?>
                        </span>
                    </div>

                    <?php if ($hasResponse): ?>

                        <div class="response-grid">
                            <div class="response-box">
                                <small>Quoted Price</small>
                                <strong>
                                    <?php echo $data['quoted_price'] !== null ? "₱" . number_format((float)$data['quoted_price'], 2) : "N/A"; ?>
                                </strong>
                            </div>

                            <div class="response-box">
                                <small>Estimated Days</small>
                                <strong>
                                    <?php echo $data['estimated_days'] !== null ? h($data['estimated_days']) . " day(s)" : "N/A"; ?>
                                </strong>
                            </div>
                        </div>

                        <div class="mt-3">
                            <small class="text-muted d-block mb-1">Remarks</small>
                            <div class="remarks-box">
                                <?php echo !empty($data['remarks']) ? nl2br(h($data['remarks'])) : "No remarks provided."; ?>
                            </div>
                        </div>

                        <div class="mt-3">
                            <small class="text-muted d-block mb-1">Response Date</small>
                            <strong><?php echo h(formatDateTime($data['submitted_at'])); ?></strong>
                        </div>

                    <?php else: ?>

                        <div class="pending-box">
                            <i class="fa-solid fa-clock"></i>
                            <div>
                                <strong>Pending response from partner</strong>
                                <p class="mb-0">The partner shop has not submitted a response yet.</p>
                            </div>
                        </div>

                    <?php endif; ?>

                </div>
            </div>

            <?php if ($canDecide): ?>
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-body p-4">

                        <h4 class="fw-bold mb-2">Final Decision</h4>
                        <p class="text-muted">
                            Accept the partner quotation to move this order to Outsourced Jobs.
                        </p>

                        <form action="save_outsourcing_decision.php" method="POST">
                            <input type="hidden" name="request_id" value="<?php echo (int)$data['id']; ?>">

                            <div class="d-grid gap-2">
                                <button type="submit" name="decision" value="accepted" class="btn btn-success">
                                    Accept and Move to Outsourced Jobs
                                </button>

                                <button type="submit" name="decision" value="held" class="btn btn-warning text-white">
                                    Hold Decision
                                </button>

                                <button type="submit" name="decision" value="declined" class="btn btn-danger">
                                    Decline
                                </button>
                            </div>
                        </form>

                    </div>
                </div>
            <?php elseif ($requestDecision === "accepted"): ?>
                <div class="success-box">
                    <i class="fa-solid fa-circle-check"></i>
                    <div>
                        <h5 class="fw-bold mb-1">Request Accepted</h5>
                        <p class="mb-0">This order has already been moved to Outsourced Jobs.</p>
                    </div>
                </div>
            <?php elseif ($requestDecision === "declined"): ?>
                <div class="declined-box">
                    <i class="fa-solid fa-circle-xmark"></i>
                    <div>
                        <h5 class="fw-bold mb-1">Request Declined</h5>
                        <p class="mb-0">This outsourcing request was declined.</p>
                    </div>
                </div>
            <?php endif; ?>

        </div>

    </div>

</div>

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

.outsourcing-details-page h1 {
    font-size: clamp(26px, 2vw, 36px);
    color: #111827;
}

.info-box {
    background: #f8fafc;
    border-radius: 16px;
    padding: 16px;
    height: 100%;
    border: 1px solid #eef2f7;
}

.info-box small,
.response-box small {
    display: block;
    color: #6b7280;
    margin-bottom: 6px;
    font-size: 13px;
}

.info-box strong,
.response-box strong {
    color: #111827;
    font-size: 15px;
}

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

.details-table tbody td {
    padding: 14px;
    color: #1f2937;
}

.instruction-box,
.remarks-box {
    background: #f8fafc;
    border: 1px solid #eef2f7;
    border-radius: 16px;
    padding: 16px;
    color: #1f2937;
    min-height: 90px;
}

.response-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 14px;
}

.response-box {
    background: #f8fafc;
    border-radius: 16px;
    padding: 16px;
    border: 1px solid #eef2f7;
}

.pending-box,
.success-box,
.declined-box {
    border-radius: 16px;
    padding: 18px;
    display: flex;
    align-items: flex-start;
    gap: 14px;
}

.pending-box {
    background: #fff7ed;
    border: 1px solid #fed7aa;
    color: #9a3412;
}

.success-box {
    background: #ecfdf5;
    border: 1px solid #bbf7d0;
    color: #166534;
}

.declined-box {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

.pending-box i,
.success-box i,
.declined-box i {
    font-size: 24px;
    margin-top: 3px;
}

@media (max-width: 768px) {
    .response-grid {
        grid-template-columns: 1fr;
    }

    .details-table {
        min-width: 620px;
    }
}
</style>