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

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

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

function getStatusText($row) {
    if (!empty($row['response_status'])) {
        return strtoupper($row['response_status']);
    }

    if (!empty($row['status'])) {
        return strtoupper($row['status']);
    }

    return "PENDING";
}

function getStatusBadgeClass($status) {
    $status = strtolower($status);

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

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

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

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

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

function formatDateTime($date) {
    if (empty($date)) {
        return "-";
    }

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

/* =========================
   SENT REQUESTS
========================= */
$sent_sql = "
    SELECT 
        r.*, 
        u.shop_name AS target_shop_name, 
        o.order_code,
        resp.response_status
    FROM outsourcing_requests r
    LEFT JOIN users u ON r.target_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.requester_shop_id = ?
    ORDER BY r.created_at DESC
";

$sent_stmt = $conn->prepare($sent_sql);
$sent_stmt->bind_param("i", $current_user_id);
$sent_stmt->execute();
$sent_requests = $sent_stmt->get_result();

/* =========================
   INCOMING REQUESTS
========================= */
$incoming_sql = "
    SELECT 
        r.*, 
        u.shop_name AS requester_shop_name, 
        o.order_code,
        resp.response_status
    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.target_shop_id = ?
    ORDER BY r.created_at DESC
";

$incoming_stmt = $conn->prepare($incoming_sql);
$incoming_stmt->bind_param("i", $current_user_id);
$incoming_stmt->execute();
$incoming_requests = $incoming_stmt->get_result();

$sent_count = $sent_requests->num_rows;
$incoming_count = $incoming_requests->num_rows;
?>

<div class="container-fluid px-4 py-4 outsourcing-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">Outsourcing Requests</h1>
            <p class="text-muted mb-0">
                Manage requests sent to partner shops and incoming outsourcing requests.
            </p>
        </div>
    </div>

    <!-- SUMMARY CARDS -->
    <div class="row g-3 mb-4">
        <div class="col-md-6 col-lg-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="summary-icon bg-primary-subtle text-primary">
                        <i class="fa-solid fa-paper-plane"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Sent Requests</p>
                        <h3 class="fw-bold mb-0"><?php echo $sent_count; ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6 col-lg-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body d-flex align-items-center gap-3">
                    <div class="summary-icon bg-info-subtle text-info">
                        <i class="fa-solid fa-inbox"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Incoming Requests</p>
                        <h3 class="fw-bold mb-0"><?php echo $incoming_count; ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- SENT REQUESTS -->
    <div class="card border-0 shadow-sm rounded-4 mb-4">
        <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div>
                    <h4 class="fw-bold mb-1">Sent Requests</h4>
                    <p class="text-muted mb-0 small">
                        Requests you sent to other shops.
                    </p>
                </div>

                <span class="badge rounded-pill bg-primary-subtle text-primary px-3 py-2">
                    <?php echo $sent_count; ?> total
                </span>
            </div>
        </div>

        <div class="card-body px-4 pb-4">
            <div class="table-responsive">
                <table class="table align-middle table-hover mb-0 custom-table">
                    <thead>
                        <tr>
                            <th>Request Code</th>
                            <th>Order</th>
                            <th>Target Shop</th>
                            <th>Status</th>
                            <th>Date Sent</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($sent_requests && $sent_requests->num_rows > 0): ?>
                            <?php while ($row = $sent_requests->fetch_assoc()): ?>
                                <?php
                                    $status = getStatusText($row);
                                    $badgeClass = getStatusBadgeClass($status);
                                ?>

                                <tr>
                                    <td>
                                        <span class="fw-semibold request-code">
                                            <?php echo clean($row['request_code']); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge bg-light text-dark border">
                                            <?php echo clean($row['order_code']); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="fw-semibold">
                                            <?php echo clean($row['target_shop_name']); ?>
                                        </div>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill <?php echo $badgeClass; ?> px-3 py-2">
                                            <?php echo clean($status); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="text-muted">
                                            <?php echo formatDateTime($row['created_at']); ?>
                                        </span>
                                    </td>

                                    <td class="text-end">
                                        <a 
                                            href="admin.php?page=view-outsourcing-request&id=<?php echo (int)$row['id']; ?>" 
                                            class="btn btn-sm btn-outline-primary rounded-pill px-3"
                                        >
                                            View
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6">
                                    <div class="empty-state">
                                        <i class="fa-solid fa-paper-plane"></i>
                                        <p class="mb-0">No sent requests yet.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- INCOMING REQUESTS -->
    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-header bg-white border-0 px-4 pt-4 pb-2">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div>
                    <h4 class="fw-bold mb-1">Incoming Requests</h4>
                    <p class="text-muted mb-0 small">
                        Requests sent by other shops to your shop.
                    </p>
                </div>

                <span class="badge rounded-pill bg-info-subtle text-info px-3 py-2">
                    <?php echo $incoming_count; ?> total
                </span>
            </div>
        </div>

        <div class="card-body px-4 pb-4">
            <div class="table-responsive">
                <table class="table align-middle table-hover mb-0 custom-table">
                    <thead>
                        <tr>
                            <th>Request Code</th>
                            <th>From Shop</th>
                            <th>Order</th>
                            <th>Status</th>
                            <th>Date Received</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($incoming_requests && $incoming_requests->num_rows > 0): ?>
                            <?php while ($row = $incoming_requests->fetch_assoc()): ?>
                                <?php
                                    $status = getStatusText($row);
                                    $badgeClass = getStatusBadgeClass($status);
                                ?>

                                <tr>
                                    <td>
                                        <span class="fw-semibold request-code">
                                            <?php echo clean($row['request_code']); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="fw-semibold">
                                            <?php echo clean($row['requester_shop_name']); ?>
                                        </div>
                                    </td>

                                    <td>
                                        <span class="badge bg-light text-dark border">
                                            <?php echo clean($row['order_code']); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill <?php echo $badgeClass; ?> px-3 py-2">
                                            <?php echo clean($status); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="text-muted">
                                            <?php echo formatDateTime($row['created_at']); ?>
                                        </span>
                                    </td>

                                    <td class="text-end">
                                        <a 
                                            href="admin.php?page=view-incoming-outsourcing-request&id=<?php echo (int)$row['id']; ?>" 
                                            class="btn btn-sm btn-primary rounded-pill px-3"
                                        >
                                            Open
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6">
                                    <div class="empty-state">
                                        <i class="fa-solid fa-inbox"></i>
                                        <p class="mb-0">No incoming requests yet.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<style>
.outsourcing-page {
    background: #f6f8fb;
    min-height: 100vh;
}

.summary-icon {
    width: 55px;
    height: 55px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
}

.custom-table thead th {
    background: #f8fafc;
    color: #111827;
    font-size: 14px;
    font-weight: 700;
    border-bottom: 1px solid #e5e7eb;
    padding: 14px;
    white-space: nowrap;
}

.custom-table tbody td {
    padding: 15px 14px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 14px;
}

.custom-table tbody tr:hover {
    background: #f9fbff;
}

.request-code {
    color: #1f2937;
    font-family: monospace;
}

.empty-state {
    padding: 35px 10px;
    text-align: center;
    color: #6b7280;
}

.empty-state i {
    font-size: 34px;
    margin-bottom: 10px;
    color: #9ca3af;
}

.card {
    overflow: hidden;
}

@media (max-width: 768px) {
    .outsourcing-page {
        padding: 18px !important;
    }

    .custom-table tbody td,
    .custom-table thead th {
        font-size: 13px;
        padding: 11px;
    }
}
</style>