<?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;

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

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

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 === "declined" || $status === "rejected") {
        return "bg-danger-subtle text-danger border border-danger-subtle";
    }

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

    return "bg-secondary-subtle text-secondary border border-secondary-subtle";
}

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

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

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

/*
|--------------------------------------------------------------------------
| LOAD REQUEST DETAILS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        r.*,
        u.shop_name AS requester_shop_name,
        o.order_code,
        o.customer_name,
        o.item_name,
        o.service_type,
        o.quantity,
        o.size,
        o.due_date,
        resp.response_status,
        resp.quoted_price,
        resp.estimated_days,
        resp.remarks,
        resp.submitted_at
    FROM outsourcing_requests r
    LEFT JOIN users u 
        ON r.requester_shop_id = u.id
    LEFT JOIN orders o 
        ON r.order_id = o.id
    LEFT JOIN outsourcing_responses resp 
        ON resp.outsourcing_request_id = r.id
    WHERE r.id = ?
      AND r.target_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.");
}

$request = $res->fetch_assoc();

/*
|--------------------------------------------------------------------------
| CHECK IF CONTRACT ALREADY ACCEPTED
|--------------------------------------------------------------------------
*/
$contractStmt = $conn->prepare("
    SELECT id
    FROM outsourcing_contract_acceptances
    WHERE outsourcing_request_id = ?
    LIMIT 1
");

$contractStmt->bind_param("i", $request_id);
$contractStmt->execute();
$contractResult = $contractStmt->get_result();
$contract_accepted = ($contractResult && $contractResult->num_rows > 0);

/*
|--------------------------------------------------------------------------
| CHECK IF ALREADY RESPONDED
|--------------------------------------------------------------------------
*/
$responseStmt = $conn->prepare("
    SELECT id
    FROM outsourcing_responses
    WHERE outsourcing_request_id = ?
    LIMIT 1
");

$responseStmt->bind_param("i", $request_id);
$responseStmt->execute();
$responseResult = $responseStmt->get_result();
$already_responded = ($responseResult && $responseResult->num_rows > 0);

$attachmentUrl = fileLink($request["attachment_file"] ?? "");
$requestStatus = !empty($request["status"]) ? ucfirst($request["status"]) : "Pending";
?>

<div class="container-fluid px-0 incoming-request-page">

    <!-- PAGE HEADER -->
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Incoming Outsourcing Request</h1>
            <p class="text-muted mb-0">
                Review the request details before accepting, declining, or submitting a 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>

    <!-- SUMMARY CARD -->
    <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 Summary</h4>
                    <p class="text-muted mb-0">
                        Main information about the outsourcing request.
                    </p>
                </div>

                <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($request["status"]); ?>">
                    <?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($request["request_code"]); ?></strong>
                    </div>
                </div>

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

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

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

            </div>

        </div>
    </div>

    <div class="row g-4">

        <!-- LEFT SIDE -->
        <div class="col-lg-7">

            <!-- ORDER DETAILS -->
            <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="table-responsive">
                        <table class="table align-middle details-table mb-0">
                            <tbody>
                                <tr>
                                    <th>Customer</th>
                                    <td><?php echo h($request["customer_name"] ?: "N/A"); ?></td>
                                </tr>

                                <tr>
                                    <th>Service Type</th>
                                    <td><?php echo h($request["service_type"] ?: "N/A"); ?></td>
                                </tr>

                                <tr>
                                    <th>Item</th>
                                    <td><?php echo h($request["item_name"] ?: "N/A"); ?></td>
                                </tr>

                                <tr>
                                    <th>Quantity</th>
                                    <td><?php echo h($request["quantity"] ?: "0"); ?></td>
                                </tr>

                                <tr>
                                    <th>Size</th>
                                    <td><?php echo h($request["size"] ?: "N/A"); ?></td>
                                </tr>

                                <tr>
                                    <th>Order Due Date</th>
                                    <td><?php echo h(formatDateOnly($request["due_date"])); ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>

            <!-- INSTRUCTIONS -->
            <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($request["request_message"])): ?>
                            <?php echo nl2br(h($request["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 Design File
                        </a>
                    <?php else: ?>
                        <p class="text-muted mb-0">
                            <i class="fa-solid fa-paperclip me-1"></i> No design file attached.
                        </p>
                    <?php endif; ?>

                </div>
            </div>

        </div>

        <!-- RIGHT SIDE -->
        <div class="col-lg-5">

            <?php if ($already_responded): ?>

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

                        <div class="success-box mb-3">
                            <i class="fa-solid fa-circle-check"></i>
                            <div>
                                <h5 class="fw-bold mb-1">Response Submitted</h5>
                                <p class="mb-0">You already responded to this request.</p>
                            </div>
                        </div>

                        <div class="response-box mb-3">
                            <small>Response Status</small>
                            <strong><?php echo h(strtoupper($request["response_status"] ?? "N/A")); ?></strong>
                        </div>

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

                            <div class="response-box">
                                <small>Estimated Days</small>
                                <strong>
                                    <?php echo $request["estimated_days"] !== null ? h($request["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($request["remarks"]) ? nl2br(h($request["remarks"])) : "No remarks provided."; ?>
                            </div>
                        </div>

                    </div>
                </div>

            <?php elseif (!$contract_accepted): ?>

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

                        <div class="warning-box mb-4">
                            <i class="fa-solid fa-file-contract"></i>
                            <div>
                                <h5 class="fw-bold mb-1">Contract Required</h5>
                                <p class="mb-0">
                                    Before you can respond, you must first review and agree to the binding contract.
                                </p>
                            </div>
                        </div>

                        <div class="d-grid gap-2">
                            <a href="admin.php?page=accept-outsourcing-contract&id=<?php echo (int)$request["id"]; ?>" class="btn btn-warning text-white">
                                Review and Accept Contract
                            </a>

                            <a href="admin.php?page=outsourcing-requests" class="btn btn-light border">
                                Cancel
                            </a>
                        </div>

                    </div>
                </div>

            <?php else: ?>

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

                        <h4 class="fw-bold mb-1">Response Form</h4>
                        <p class="text-muted mb-4">
                            Submit your quotation and estimated production time.
                        </p>

                        <form id="responseForm" action="save_outsourcing_response.php" method="POST">
                            <input type="hidden" name="request_id" value="<?php echo (int)$request["id"]; ?>">
                            <input type="hidden" name="response_status" id="response_status" value="">

                            <div class="mb-3">
                                <label class="form-label fw-semibold">Quoted Price</label>
                                <input type="number" step="0.01" name="quoted_price" id="quoted_price" class="form-control" placeholder="Enter quoted price">
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-semibold">Estimated Days</label>
                                <input type="number" name="estimated_days" id="estimated_days" class="form-control" placeholder="Enter estimated days">
                            </div>

                            <div class="mb-4">
                                <label class="form-label fw-semibold">Remarks</label>
                                <textarea name="remarks" id="remarks" rows="5" class="form-control" placeholder="Add remarks or production notes..."></textarea>
                            </div>

                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" onclick="submitDecline()" class="btn btn-outline-danger px-4">
                                    Decline
                                </button>

                                <button type="button" onclick="submitAccept()" class="btn btn-primary px-4">
                                    Submit Response
                                </button>

                                <a href="admin.php?page=outsourcing-requests" class="btn btn-light border px-4">
                                    Cancel
                                </a>
                            </div>
                        </form>

                    </div>
                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

<style>
.incoming-request-page {
    width: 100%;
}

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

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

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

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

.details-table th {
    width: 180px;
    background: #f8fafc;
    color: #111827;
    font-weight: 700;
    padding: 14px;
}

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

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

.warning-box {
    background: #fff7ed;
    border: 1px solid #fed7aa;
    color: #9a3412;
    border-radius: 16px;
    padding: 18px;
    display: flex;
    gap: 14px;
}

.warning-box i {
    font-size: 26px;
    margin-top: 2px;
}

.success-box {
    background: #ecfdf5;
    border: 1px solid #bbf7d0;
    color: #166534;
    border-radius: 16px;
    padding: 18px;
    display: flex;
    gap: 14px;
}

.success-box i {
    font-size: 26px;
    margin-top: 2px;
}

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

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

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

@media (max-width: 768px) {
    .details-table th,
    .details-table td {
        display: block;
        width: 100%;
    }

    .details-table th {
        border-bottom: 0;
        padding-bottom: 4px;
    }

    .details-table td {
        padding-top: 4px;
    }

    .response-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
function submitDecline() {
    if (!confirm("Are you sure you want to decline this request?")) {
        return;
    }

    document.getElementById("response_status").value = "declined";
    document.getElementById("responseForm").submit();
}

function submitAccept() {
    const price = document.getElementById("quoted_price").value.trim();
    const days = document.getElementById("estimated_days").value.trim();

    if (price === "") {
        alert("Please enter quoted price before submitting response.");
        return;
    }

    if (days === "") {
        alert("Please enter estimated days before submitting response.");
        return;
    }

    document.getElementById("response_status").value = "accepted";
    document.getElementById("responseForm").submit();
}
</script>