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

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

if (!isset($_SESSION["user_id"])) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$shop_id = (int) $_SESSION["user_id"];

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

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

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

function formatMoney($amount)
{
    return "₱" . number_format((float)($amount ?? 0), 2);
}

function displayStatus($status)
{
    if (empty($status)) {
        return "N/A";
    }

    return ucwords(str_replace("_", " ", $status));
}

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

    switch ($status) {
        case "paid":
            return "bg-success-subtle text-success border border-success-subtle";
        case "computed":
            return "bg-primary-subtle text-primary border border-primary-subtle";
        case "pending":
            return "bg-warning-subtle text-warning-emphasis border border-warning-subtle";
        case "cancelled":
            return "bg-danger-subtle text-danger border border-danger-subtle";
        default:
            return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    }
}

function jobStatusBadgeClass($status)
{
    $status = strtolower((string)($status ?? ""));

    switch ($status) {
        case "assigned":
            return "bg-info-subtle text-info border border-info-subtle";
        case "in_progress":
            return "bg-primary-subtle text-primary border border-primary-subtle";
        case "completed":
            return "bg-success-subtle text-success border border-success-subtle";
        case "cancelled":
            return "bg-danger-subtle text-danger border border-danger-subtle";
        default:
            return "bg-secondary-subtle text-secondary border border-secondary-subtle";
    }
}

/*
|--------------------------------------------------------------------------
| UPDATE COMMISSION
|--------------------------------------------------------------------------
*/

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["update_commission"])) {
    $job_id = (int)($_POST["job_id"] ?? 0);
    $commission_rate = (float)($_POST["commission_rate"] ?? 10);
    $commission_status = $_POST["commission_status"] ?? "computed";

    if ($commission_rate < 0) {
        $commission_rate = 0;
    }

    if ($commission_rate > 100) {
        $commission_rate = 100;
    }

    $allowed_status = ["pending", "computed", "paid", "cancelled"];

    if (!in_array($commission_status, $allowed_status, true)) {
        $commission_status = "computed";
    }

    $stmt = $conn->prepare("
        UPDATE outsourced_jobs
        SET 
            commission_rate = ?,
            commission_amount = awarded_price * (? / 100),
            executor_earning = awarded_price - (awarded_price * (? / 100)),
            commission_status = ?
        WHERE id = ?
        AND (original_shop_id = ? OR executor_shop_id = ?)
    ");

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

    $stmt->bind_param(
        "dddsiii",
        $commission_rate,
        $commission_rate,
        $commission_rate,
        $commission_status,
        $job_id,
        $shop_id,
        $shop_id
    );

    if ($stmt->execute()) {
        $_SESSION["success_message"] = "Commission updated successfully.";
    } else {
        $_SESSION["error_message"] = "Failed to update commission.";
    }

    echo "<script>window.location='admin.php?page=commission';</script>";
    exit();
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

$from_date = $_GET["from_date"] ?? "";
$to_date = $_GET["to_date"] ?? "";
$status_filter = $_GET["status"] ?? "";
$search = trim($_GET["search"] ?? "");

$where = " WHERE (j.original_shop_id = ? OR j.executor_shop_id = ?) ";
$params = [$shop_id, $shop_id];
$types = "ii";

if (!empty($from_date) && !empty($to_date)) {
    $where .= " AND DATE(j.created_at) BETWEEN ? AND ? ";
    $params[] = $from_date;
    $params[] = $to_date;
    $types .= "ss";
} elseif (!empty($from_date)) {
    $where .= " AND DATE(j.created_at) >= ? ";
    $params[] = $from_date;
    $types .= "s";
} elseif (!empty($to_date)) {
    $where .= " AND DATE(j.created_at) <= ? ";
    $params[] = $to_date;
    $types .= "s";
}

if (!empty($status_filter)) {
    $where .= " AND j.commission_status = ? ";
    $params[] = $status_filter;
    $types .= "s";
}

if (!empty($search)) {
    $where .= " AND (
        o.order_code LIKE ?
        OR o.customer_name LIKE ?
        OR original_shop.shop_name LIKE ?
        OR executor_shop.shop_name LIKE ?
    ) ";

    $searchTerm = "%" . $search . "%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= "ssss";
}

/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/

$summarySql = "
    SELECT
        COUNT(j.id) AS total_jobs,
        COALESCE(SUM(j.awarded_price), 0) AS total_awarded_price,
        COALESCE(SUM(j.commission_amount), 0) AS total_commission,
        COALESCE(SUM(j.executor_earning), 0) AS total_executor_earning,
        SUM(CASE WHEN j.commission_status = 'paid' THEN 1 ELSE 0 END) AS paid_count,
        SUM(CASE WHEN j.commission_status = 'pending' THEN 1 ELSE 0 END) AS pending_count
    FROM outsourced_jobs j
    LEFT JOIN orders o ON j.order_id = o.id
    LEFT JOIN users original_shop ON j.original_shop_id = original_shop.id
    LEFT JOIN users executor_shop ON j.executor_shop_id = executor_shop.id
    $where
";

$summaryStmt = $conn->prepare($summarySql);

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

$summaryStmt->bind_param($types, ...$params);
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc();

$total_jobs = (int)($summary["total_jobs"] ?? 0);
$total_awarded_price = (float)($summary["total_awarded_price"] ?? 0);
$total_commission = (float)($summary["total_commission"] ?? 0);
$total_executor_earning = (float)($summary["total_executor_earning"] ?? 0);
$paid_count = (int)($summary["paid_count"] ?? 0);
$pending_count = (int)($summary["pending_count"] ?? 0);

/*
|--------------------------------------------------------------------------
| COMMISSION LIST
|--------------------------------------------------------------------------
*/

$listSql = "
    SELECT
        j.id AS job_id,
        j.awarded_price,
        j.commission_rate,
        j.commission_amount,
        j.executor_earning,
        j.commission_status,
        j.status AS job_status,
        j.awarded_at,
        j.created_at,

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

        original_shop.shop_name AS original_shop_name,
        executor_shop.shop_name AS executor_shop_name,

        CASE 
            WHEN j.original_shop_id = ? THEN 'Original Shop'
            WHEN j.executor_shop_id = ? THEN 'Executor Shop'
            ELSE 'Shop'
        END AS shop_role

    FROM outsourced_jobs j
    LEFT JOIN orders o ON j.order_id = o.id
    LEFT JOIN users original_shop ON j.original_shop_id = original_shop.id
    LEFT JOIN users executor_shop ON j.executor_shop_id = executor_shop.id
    $where
    ORDER BY j.created_at DESC
";

$listParams = array_merge([$shop_id, $shop_id], $params);
$listTypes = "ii" . $types;

$listStmt = $conn->prepare($listSql);

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

$listStmt->bind_param($listTypes, ...$listParams);
$listStmt->execute();
$commissions = $listStmt->get_result();
?>

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

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Commission</h1>
            <p class="text-muted mb-0">
                Monitor and compute commissions for outsourced jobs.
            </p>
        </div>

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

    <?php if (!empty($_SESSION["success_message"])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo h($_SESSION["success_message"]); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION["success_message"]); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION["error_message"])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo h($_SESSION["error_message"]); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION["error_message"]); ?>
    <?php endif; ?>

    <div class="row g-3 mb-4">
        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-primary-subtle text-primary">
                    <i class="fa-solid fa-briefcase"></i>
                </div>
                <div>
                    <p>Total Jobs</p>
                    <h3><?php echo $total_jobs; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-info-subtle text-info">
                    <i class="fa-solid fa-hand-holding-dollar"></i>
                </div>
                <div>
                    <p>Awarded Price</p>
                    <h3 class="money-stat"><?php echo formatMoney($total_awarded_price); ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-warning-subtle text-warning-emphasis">
                    <i class="fa-solid fa-percent"></i>
                </div>
                <div>
                    <p>Commission</p>
                    <h3 class="money-stat"><?php echo formatMoney($total_commission); ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="fa-solid fa-peso-sign"></i>
                </div>
                <div>
                    <p>Executor Earning</p>
                    <h3 class="money-stat"><?php echo formatMoney($total_executor_earning); ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-success-subtle text-success">
                    <i class="fa-solid fa-circle-check"></i>
                </div>
                <div>
                    <p>Paid</p>
                    <h3><?php echo $paid_count; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-2">
            <div class="commission-stat-card">
                <div class="stat-icon bg-danger-subtle text-danger">
                    <i class="fa-solid fa-clock"></i>
                </div>
                <div>
                    <p>Pending</p>
                    <h3><?php echo $pending_count; ?></h3>
                </div>
            </div>
        </div>
    </div>

   

    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                <div>
                    <h4 class="fw-bold mb-1">Commission Records</h4>
                    <p class="text-muted mb-0 small">
                        Default formula: Commission Amount = Awarded Price × Commission Rate.
                    </p>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0 commission-table">
                    <thead>
                        <tr>
                            <th>Order Code</th>
                            <th>Customer</th>
                            <th>Original Shop</th>
                            <th>Executor Shop</th>
                            <th>Your Role</th>
                            <th>Item</th>
                            <th>Awarded Price</th>
                            <th>Rate</th>
                            <th>Commission</th>
                            <th>Executor Earning</th>
                            <th>Job Status</th>
                            <th>Commission Status</th>
                            <th>Awarded At</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if ($commissions && $commissions->num_rows > 0): ?>
                            <?php while ($row = $commissions->fetch_assoc()): ?>
                                <tr>
                                    <td class="fw-semibold">
                                        <?php echo h($row["order_code"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["customer_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["original_shop_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo h($row["executor_shop_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill bg-light text-dark border px-3 py-2">
                                            <?php echo h($row["shop_role"]); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php echo h($row["item_name"] ?: "N/A"); ?>
                                    </td>

                                    <td>
                                        <?php echo formatMoney($row["awarded_price"]); ?>
                                    </td>

                                    <td>
                                        <?php echo number_format((float)$row["commission_rate"], 2); ?>%
                                    </td>

                                    <td class="fw-semibold text-primary">
                                        <?php echo formatMoney($row["commission_amount"]); ?>
                                    </td>

                                    <td class="fw-semibold text-success">
                                        <?php echo formatMoney($row["executor_earning"]); ?>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill px-3 py-2 <?php echo jobStatusBadgeClass($row["job_status"]); ?>">
                                            <?php echo h(displayStatus($row["job_status"])); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge rounded-pill px-3 py-2 <?php echo statusBadgeClass($row["commission_status"]); ?>">
                                            <?php echo h(displayStatus($row["commission_status"])); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php echo h(formatDateOnly($row["awarded_at"])); ?>
                                    </td>

                                    <td>
                                        <button 
                                            type="button"
                                            class="btn btn-sm btn-outline-primary rounded-pill px-3"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editCommissionModal<?php echo (int)$row["job_id"]; ?>"
                                        >
                                            Edit
                                        </button>
                                    </td>
                                </tr>

                                <div class="modal fade" id="editCommissionModal<?php echo (int)$row["job_id"]; ?>" tabindex="-1">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content border-0 rounded-4">
                                            <form method="POST">
                                                <div class="modal-header">
                                                    <h5 class="modal-title fw-bold">
                                                        Update Commission
                                                    </h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>

                                                <div class="modal-body">
                                                    <input type="hidden" name="job_id" value="<?php echo (int)$row["job_id"]; ?>">

                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Order Code</label>
                                                        <input 
                                                            type="text" 
                                                            class="form-control" 
                                                            value="<?php echo h($row["order_code"]); ?>" 
                                                            readonly
                                                        >
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Awarded Price</label>
                                                        <input 
                                                            type="text" 
                                                            class="form-control" 
                                                            value="<?php echo h(formatMoney($row["awarded_price"])); ?>" 
                                                            readonly
                                                        >
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Commission Rate (%)</label>
                                                        <input 
                                                            type="number" 
                                                            name="commission_rate" 
                                                            class="form-control"
                                                            min="0"
                                                            max="100"
                                                            step="0.01"
                                                            value="<?php echo h($row["commission_rate"]); ?>"
                                                            required
                                                        >
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label fw-semibold">Commission Status</label>
                                                        <select name="commission_status" class="form-select" required>
                                                            <option value="pending" <?php echo $row["commission_status"] === "pending" ? "selected" : ""; ?>>Pending</option>
                                                            <option value="computed" <?php echo $row["commission_status"] === "computed" ? "selected" : ""; ?>>Computed</option>
                                                            <option value="paid" <?php echo $row["commission_status"] === "paid" ? "selected" : ""; ?>>Paid</option>
                                                            <option value="cancelled" <?php echo $row["commission_status"] === "cancelled" ? "selected" : ""; ?>>Cancelled</option>
                                                        </select>
                                                    </div>

                                                    <div class="alert alert-light border mb-0">
                                                        The system will automatically recompute the commission amount and executor earning after saving.
                                                    </div>
                                                </div>

                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">
                                                        Cancel
                                                    </button>

                                                    <button type="submit" name="update_commission" class="btn btn-primary">
                                                        Save Changes
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="14" class="text-center text-muted py-5">
                                    No commission records found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<style>
.commission-page {
    width: 100%;
    max-width: 100%;
    overflow-x: hidden;
}

.commission-page h1 {
    font-size: clamp(26px, 2.2vw, 38px);
    color: #111827;
}

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

.btn {
    border-radius: 10px;
}

.commission-stat-card {
    background: #ffffff;
    border-radius: 18px;
    padding: 18px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    gap: 12px;
    height: 100%;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}

.commission-stat-card p {
    margin: 0 0 4px;
    color: #6b7280;
    font-size: 13px;
}

.commission-stat-card h3 {
    margin: 0;
    font-size: 26px;
    font-weight: 800;
    color: #111827;
}

.commission-stat-card .money-stat {
    font-size: 18px;
}

.commission-table {
    min-width: 1500px;
}

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

.commission-table tbody td {
    padding: 14px;
    font-size: 13px;
    white-space: nowrap;
    border-bottom: 1px solid #f0f0f0;
}

.commission-table tbody tr:hover {
    background: #f9fafb;
}

.modal-content {
    box-shadow: 0 18px 50px rgba(0, 0, 0, 0.16);
}

@media (max-width: 768px) {
    .commission-table {
        min-width: 1300px;
    }

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