<?php
ob_start();
session_start();
require_once '../config/database.php';       // $pdo (Seven Credit DB)
require_once '../config/modules.php';         // company_enabled_modules(), module_on()
require_once '../config/module_access.php';   // mod_can_view(), mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId   = (int)$_SESSION['company_id'];
$userId      = (int)$_SESSION['user_id'];
$role        = $_SESSION['role'] ?? '';
$companyName = $_SESSION['company_name'] ?? 'Company';

$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'jobs')) {
    http_response_code(403);
    exit('Job Management is not enabled for your company.');
}
if (!mod_can_admin($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403);
    exit('You need Manage (admin) access for Job Management.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

/*
|--------------------------------------------------------------------------
| Helper: pretty job number (JOB-YYYYMMDDHHMMSS -> dd/mm/YYYY (HHMMSS))
|--------------------------------------------------------------------------
*/
function formatJobNo($jobNo)
{
    $jobNo = (string)$jobNo;
    if (preg_match('/JOB-(\d{8})(\d{6})/', $jobNo, $matches)) {
        $dateRaw = $matches[1];
        $time    = $matches[2];
        $dateObj = DateTime::createFromFormat('Ymd', $dateRaw);
        $dateFormatted = $dateObj ? $dateObj->format('d/m/Y') : $dateRaw;
        return $dateFormatted . ' (' . $time . ')';
    }
    return $jobNo;
}

/*
|--------------------------------------------------------------------------
| Filter (Year / Month From-To)
|--------------------------------------------------------------------------
*/
$year      = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$monthFrom = isset($_GET['month_from']) ? (int)$_GET['month_from'] : (int)date('n');
$monthTo   = isset($_GET['month_to']) ? (int)$_GET['month_to'] : (int)date('n');

if ($year < 2000 || $year > 2100) { $year = (int)date('Y'); }
if ($monthFrom < 1 || $monthFrom > 12) { $monthFrom = (int)date('n'); }
if ($monthTo   < 1 || $monthTo   > 12) { $monthTo   = (int)date('n'); }
if ($monthFrom > $monthTo) { [$monthFrom, $monthTo] = [$monthTo, $monthFrom]; }

/*
|--------------------------------------------------------------------------
| Total Payment Summary (share of staff_fee across assigned staff),
| scoped by company_id, closed jobs only.
|--------------------------------------------------------------------------
*/
$totalPayment = 0;
try {
    $totalPaymentStmt = $pdo->prepare("
        SELECT COALESCE(SUM(job_split.share_amount), 0) AS total_payment
        FROM (
            SELECT
                j.id AS job_id,
                js.user_id,
                ROUND(
                    j.staff_fee / NULLIF((
                        SELECT COUNT(*)
                        FROM sp_job_staff js2
                        WHERE js2.company_id = :c1 AND js2.job_id = j.id
                    ), 0),
                0) AS share_amount
            FROM sp_jobs j
            INNER JOIN sp_job_staff js
                ON js.company_id = j.company_id AND js.job_id = j.id
            WHERE j.company_id = :c2
              AND j.status = 'closed'
              AND j.closed_at IS NOT NULL
              AND YEAR(j.closed_at) = :year
              AND MONTH(j.closed_at) BETWEEN :month_from AND :month_to
        ) AS job_split
    ");
    $totalPaymentStmt->execute([
        ':c1' => $companyId,
        ':c2' => $companyId,
        ':year' => $year,
        ':month_from' => $monthFrom,
        ':month_to' => $monthTo,
    ]);
    $totalPayment = $totalPaymentStmt->fetch(PDO::FETCH_ASSOC)['total_payment'] ?? 0;
} catch (Throwable $e) {
    $totalPayment = 0;
}

/*
|--------------------------------------------------------------------------
| Staff Summary — company users (via company_staff), attributed shares,
| grouped by staff.
|--------------------------------------------------------------------------
*/
$staffSummaries = [];
try {
    $staffSummaryStmt = $pdo->prepare("
        SELECT
            u.id,
            u.name AS full_name,
            cs.staff_code,
            COUNT(CASE WHEN j.status = 'closed' THEN 1 END) AS total_closed_jobs,
            COALESCE(SUM(
                CASE
                    WHEN j.status = 'closed' THEN
                        ROUND(
                            j.staff_fee / NULLIF((
                                SELECT COUNT(*)
                                FROM sp_job_staff js2
                                WHERE js2.company_id = j.company_id AND js2.job_id = j.id
                            ), 0),
                        0)
                    ELSE 0
                END
            ), 0) AS total_earned
        FROM company_staff cs
        INNER JOIN users u ON u.id = cs.user_id
        LEFT JOIN sp_job_staff js
            ON js.company_id = cs.company_id AND js.user_id = u.id
        LEFT JOIN sp_jobs j
            ON j.company_id = cs.company_id
            AND j.id = js.job_id
            AND j.status = 'closed'
            AND j.closed_at IS NOT NULL
            AND YEAR(j.closed_at) = :year
            AND MONTH(j.closed_at) BETWEEN :month_from AND :month_to
        WHERE cs.company_id = :company_id
        GROUP BY u.id, u.name, cs.staff_code
        ORDER BY total_earned DESC, u.name ASC
    ");
    $staffSummaryStmt->execute([
        ':company_id' => $companyId,
        ':year' => $year,
        ':month_from' => $monthFrom,
        ':month_to' => $monthTo,
    ]);
    $staffSummaries = $staffSummaryStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $staffSummaries = [];
}

/*
|--------------------------------------------------------------------------
| Staff Jobs — closed jobs attributed to each staff, scoped by company_id.
|--------------------------------------------------------------------------
*/
$staffJobsRaw = [];
try {
    $staffJobsStmt = $pdo->prepare("
        SELECT
            u.id AS staff_id,
            u.name AS full_name,
            j.id AS job_id,
            j.job_no,
            j.issue_title,
            j.status AS job_status,
            j.staff_fee,
            j.closed_at,
            j.sd_no,
            j.machine_no,
            ROUND(
                j.staff_fee / NULLIF((
                    SELECT COUNT(*)
                    FROM sp_job_staff js2
                    WHERE js2.company_id = j.company_id AND js2.job_id = j.id
                ), 0),
            0) AS share_amount
        FROM company_staff cs
        INNER JOIN users u ON u.id = cs.user_id
        INNER JOIN sp_job_staff js
            ON js.company_id = cs.company_id AND js.user_id = u.id
        INNER JOIN sp_jobs j
            ON j.company_id = cs.company_id AND j.id = js.job_id
        WHERE cs.company_id = :company_id
          AND j.status = 'closed'
          AND j.closed_at IS NOT NULL
          AND YEAR(j.closed_at) = :year
          AND MONTH(j.closed_at) BETWEEN :month_from AND :month_to
        ORDER BY u.name ASC, j.id DESC
    ");
    $staffJobsStmt->execute([
        ':company_id' => $companyId,
        ':year' => $year,
        ':month_from' => $monthFrom,
        ':month_to' => $monthTo,
    ]);
    $staffJobsRaw = $staffJobsStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $staffJobsRaw = [];
}

/*
|--------------------------------------------------------------------------
| Map Jobs by staff id
|--------------------------------------------------------------------------
*/
$staffJobsMap = [];
foreach ($staffJobsRaw as $row) {
    $staffJobsMap[$row['staff_id']][] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Payment</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #f3f6fb;
            --card: #ffffff;
            --ink: #111827;
            --muted: #64748b;
            --line: #eaeef5;
            --brand: #2563eb;
            --brand2: #1d4ed8;
            --shadow: 0 12px 30px rgba(30, 41, 59, 0.08);
            --shadow-sm: 0 2px 6px rgba(30, 41, 59, 0.06);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Noto Sans Lao', 'Inter', Arial, sans-serif;
            background: var(--bg);
            color: var(--ink);
            -webkit-font-smoothing: antialiased;
        }
        .wrap { max-width: 1300px; margin: 0 auto; padding: 24px 16px 48px; }

        /* Dark top strip */
        .strip {
            background: #0f172a; color: #e2e8f0;
            border-radius: 16px; padding: 14px 20px; margin-bottom: 20px;
            display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
        }
        .strip .brand { font-weight: 800; letter-spacing: .3px; font-size: 16px; color: #fff; }
        .strip .company { color: #94a3b8; font-weight: 600; font-size: 14px; }

        /* Nav bar */
        .navbar { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 22px; }
        .navbar a {
            background: #fff; border: 1px solid var(--line); padding: 9px 14px;
            border-radius: 999px; text-decoration: none; color: #475569; font-weight: 600;
            font-size: 14px; transition: all .15s ease; box-shadow: var(--shadow-sm);
        }
        .navbar a:hover { color: var(--brand); border-color: #bfdbfe; transform: translateY(-1px); }
        .navbar a.active { background: #eff6ff; border-color: #93c5fd; color: var(--brand); }
        .navbar a.logout { color: #b91c1c; }
        .navbar a.logout:hover { color: #991b1b; border-color: #fecaca; }

        .page-head { margin-bottom: 18px; }
        .page-head h1 { margin: 0; font-size: 26px; font-weight: 800; letter-spacing: -0.02em; }

        .card {
            background: var(--card); border: 1px solid var(--line); border-radius: 20px;
            box-shadow: var(--shadow); padding: 22px; margin-bottom: 20px;
        }
        .section-title { margin-top: 0; margin-bottom: 16px; font-size: 20px; font-weight: 700; }

        .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }
        .summary-box { background: #f8fafc; border: 1px solid var(--line); border-radius: 14px; padding: 18px; }
        .summary-label { color: var(--muted); font-size: 13px; margin-bottom: 8px; font-weight: 600; }
        .summary-value { font-size: 28px; font-weight: 800; }

        /* Filter toolbar */
        .filter-form {
            display: flex; align-items: flex-end; gap: 12px; flex-wrap: wrap;
            background: #f8fafc; border: 1px solid var(--line); border-radius: 14px; padding: 14px; margin-bottom: 18px;
        }
        .filter-group { display: flex; flex-direction: column; gap: 6px; }
        .filter-group label { font-size: 13px; font-weight: 600; color: var(--muted); }
        .filter-group input[type="number"], .filter-group select {
            padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 10px;
            background: #fff; font-size: 14px; font-family: inherit; min-width: 110px; text-align: center;
        }
        .btn {
            background: var(--brand); color: #fff; border: none; padding: 11px 18px; border-radius: 10px;
            font-weight: 700; cursor: pointer; font-size: 14px; font-family: inherit; text-decoration: none;
            display: inline-flex; align-items: center; transition: all .15s ease;
        }
        .btn:hover { background: var(--brand2); transform: translateY(-1px); }

        .table-scroll { overflow-x: auto; border-radius: 14px; -webkit-overflow-scrolling: touch; }
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        thead th {
            background: #f8fafc; color: var(--muted); text-transform: uppercase;
            font-size: 11px; letter-spacing: .05em; font-weight: 700;
            padding: 12px; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap;
        }
        tbody td { padding: 12px; border-bottom: 1px solid var(--line); text-align: left; font-size: 14px; vertical-align: top; }
        .muted { color: var(--muted); }

        .staff-block { background: var(--card); border: 1px solid var(--line); border-radius: 20px; box-shadow: var(--shadow); padding: 20px; margin-bottom: 20px; }
        .staff-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
        .staff-name { font-size: 20px; font-weight: 800; margin-bottom: 4px; }
        .staff-meta { color: var(--muted); font-size: 14px; }
        .earned-badge { background: #dcfce7; color: #166534; padding: 10px 14px; border-radius: 999px; font-weight: 700; white-space: nowrap; }

        .status { display: inline-block; padding: 6px 11px; border-radius: 999px; font-size: 12px; font-weight: 700; white-space: nowrap; }
        .status-closed { background: #dcfce7; color: #166534; }
        .status-open   { background: #dbeafe; color: #1d4ed8; }

        .grand-total-row { background: #f8fafc; font-weight: 800; }

        @media (max-width: 700px) {
            .summary-value { font-size: 22px; }
            .page-head h1 { font-size: 22px; }
        }
    </style>
</head>
<body>
    <div class="wrap">

        <div class="strip">
            <span class="brand">Seven Credit &middot; Job Management</span>
            <span class="company"><?= esc($companyName) ?></span>
        </div>

        <div class="navbar">
            <a href="sp_jobs_admin.php">Dashboard</a>
            <a href="sp_job_add.php">Open Job</a>
            <a href="../company/staff.php">Staff</a>
            <a href="sp_staff_payments.php" class="active">Staff Payment</a>
            <a href="sp_payment_types.php">Payment Types</a>
            <a href="dashboard.php">Back to Company</a>
            <a href="../auth/logout.php" class="logout">Logout</a>
        </div>

        <div class="page-head">
            <h1>Staff Payment</h1>
        </div>

        <div class="card">
            <h2 class="section-title">Payment Summary</h2>
            <div class="summary-grid">
                <div class="summary-box">
                    <div class="summary-label">Total Payment to All Staff</div>
                    <div class="summary-value"><?= number_format((float)$totalPayment, 0) ?> LAK</div>
                </div>
                <div class="summary-box">
                    <div class="summary-label">Total Staff Count</div>
                    <div class="summary-value"><?= count($staffSummaries) ?></div>
                </div>
            </div>
        </div>

        <div class="card">
            <form method="GET" class="filter-form">
                <div class="filter-group">
                    <label for="year">Year</label>
                    <input type="number" id="year" name="year" min="2000" max="2100" value="<?= esc($year) ?>">
                </div>
                <div class="filter-group">
                    <label for="month_from">From</label>
                    <select id="month_from" name="month_from">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?= $m ?>" <?= $m == $monthFrom ? 'selected' : '' ?>><?= $m ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="month_to">To</label>
                    <select id="month_to" name="month_to">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?= $m ?>" <?= $m == $monthTo ? 'selected' : '' ?>><?= $m ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <button type="submit" class="btn">Filter</button>
            </form>

            <h2 class="section-title">Staff Payment Summary Table</h2>

            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th>Staff Name</th>
                            <th>Staff Code</th>
                            <th>Closed Jobs</th>
                            <th>Total Earned</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($staffSummaries): ?>
                            <?php foreach ($staffSummaries as $staff): ?>
                                <tr>
                                    <td><?= esc($staff['full_name']) ?></td>
                                    <td><?= esc($staff['staff_code'] ?: '-') ?></td>
                                    <td><?= esc($staff['total_closed_jobs']) ?></td>
                                    <td><strong><?= number_format((float)$staff['total_earned'], 0) ?> LAK</strong></td>
                                </tr>
                            <?php endforeach; ?>

                            <tr class="grand-total-row">
                                <td colspan="3" style="text-align:right;">Grand Total Payment</td>
                                <td><?= number_format((float)$totalPayment, 0) ?> LAK</td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="muted">No staff records found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php foreach ($staffSummaries as $staff): ?>
            <div class="staff-block">
                <div class="staff-header">
                    <div>
                        <div class="staff-name"><?= esc($staff['full_name']) ?></div>
                        <div class="staff-meta">
                            Staff Code: <?= esc($staff['staff_code'] ?: '-') ?> |
                            Closed Jobs: <?= esc($staff['total_closed_jobs']) ?>
                        </div>
                    </div>
                    <div class="earned-badge">
                        Total Earned: <?= number_format((float)$staff['total_earned'], 0) ?> LAK
                    </div>
                </div>

                <div class="table-scroll">
                    <table>
                        <thead>
                            <tr>
                                <th>Job No</th>
                                <th>Customer (SD)</th>
                                <th>Machine</th>
                                <th>Issue</th>
                                <th>Job Status</th>
                                <th>Job Staff Fee</th>
                                <th>This Staff Share</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($staffJobsMap[$staff['id']])): ?>
                                <?php foreach ($staffJobsMap[$staff['id']] as $job): ?>
                                    <tr>
                                        <td><?= esc(formatJobNo($job['job_no'])) ?></td>
                                        <td><?= esc($job['sd_no'] ?: '-') ?></td>
                                        <td><?= esc($job['machine_no'] ?: '-') ?></td>
                                        <td><?= esc($job['issue_title'] ?: '-') ?></td>
                                        <td>
                                            <span class="status status-closed">
                                                <?= esc(ucwords(str_replace('_', ' ', (string)$job['job_status']))) ?>
                                            </span>
                                        </td>
                                        <td><?= number_format((float)$job['staff_fee'], 0) ?> LAK</td>
                                        <td><strong><?= number_format((float)$job['share_amount'], 0) ?> LAK</strong></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="muted">No closed jobs in this period.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>

    </div>
</body>
</html>
<?php ob_end_flush(); ?>