<?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_edit($pdo, $companyId, $userId, $role, 'jobs')) {
    http_response_code(403);
    exit('You do not have access to Job Management.');
}
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
$staffName = $_SESSION['name'] ?? 'Staff';

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/
function jobShareAmount($staffFee, $assignedCount)
{
    if ((int)$assignedCount <= 0) {
        return 0;
    }
    return round($staffFee / $assignedCount);
}

/*
|--------------------------------------------------------------------------
| Payment type labels for this company (code => label)
|--------------------------------------------------------------------------
*/
$paymentTypeMap = [];
try {
    $ptStmt = $pdo->prepare("SELECT code, label FROM sp_payment_types WHERE company_id = ? ORDER BY label ASC");
    $ptStmt->execute([$companyId]);
    foreach ($ptStmt->fetchAll(PDO::FETCH_ASSOC) as $p) {
        if (($p['code'] ?? '') !== '') {
            $paymentTypeMap[$p['code']] = $p['label'];
        }
    }
} catch (Throwable $e) {
    $paymentTypeMap = [];
}
function paymentTypeLabel($paymentType, $paymentTypeMap)
{
    $paymentType = (string)$paymentType;
    if (isset($paymentTypeMap[$paymentType])) {
        return $paymentTypeMap[$paymentType];
    }
    return $paymentType !== '' ? ucwords(str_replace('_', ' ', $paymentType)) : 'Other';
}

/*
|--------------------------------------------------------------------------
| Staff Summary  (only this user's jobs, scoped by company_id + user_id)
|  - Total Jobs        = count of assigned jobs
|  - Completed Jobs    = status = 'closed'
|  - Incomplete Jobs   = status <> 'closed'
|  - Total Earned      = sum of the CLOSED jobs' per-staff share (staff_fee
|                        split evenly among all assigned technicians)
|--------------------------------------------------------------------------
*/
$summaryStmt = $pdo->prepare("
    SELECT
        COUNT(*) AS total_jobs,
        COUNT(CASE WHEN j.status = 'closed' THEN 1 END)  AS total_closed_jobs,
        COUNT(CASE WHEN j.status <> 'closed' THEN 1 END) AS total_incomplete_jobs,
        COALESCE(SUM(
            CASE
                WHEN j.status = 'closed' THEN
                    ROUND(
                        j.staff_fee / NULLIF((
                            SELECT COUNT(*)
                            FROM sp_job_staff jss2
                            WHERE jss2.company_id = j.company_id
                              AND jss2.job_id = j.id
                        ), 0),
                    0)
                ELSE 0
            END
        ), 0) AS total_earned
    FROM sp_jobs j
    INNER JOIN sp_job_staff jss
        ON jss.company_id = j.company_id AND jss.job_id = j.id
    WHERE j.company_id = ? AND jss.user_id = ?
");
$summaryStmt->execute([$companyId, $userId]);
$summary = $summaryStmt->fetch(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| This staff's job list (company + user scoped)
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT
        j.id,
        j.job_no,
        j.job_type,
        j.sd_no,
        j.machine_id,
        j.machine_no,
        j.issue_title,
        j.issue_description,
        j.priority,
        j.payment_type,
        j.staff_fee,
        j.status,
        j.open_date,
        j.closed_at,
        j.created_at,
        COALESCE(NULLIF(c.customer_name,''), cm.customer_name) AS customer_name,
        m.unique_machine_no AS unique_machine_no,
        m.machine_model     AS machine_model,
        (
            SELECT COUNT(*)
            FROM sp_job_staff jss2
            WHERE jss2.company_id = j.company_id
              AND jss2.job_id = j.id
        ) AS assigned_staff_count
    FROM sp_jobs j
    INNER JOIN sp_job_staff jss
        ON jss.company_id = j.company_id AND jss.job_id = j.id
    LEFT JOIN sp_machines  m ON m.company_id = j.company_id AND m.id   = j.machine_id
    LEFT JOIN sp_customers c ON c.company_id = j.company_id AND c.sd_no = j.sd_no
    LEFT JOIN sp_customers cm ON cm.company_id = j.company_id AND cm.sd_no = m.sd_no
    WHERE j.company_id = ? AND jss.user_id = ?
    ORDER BY
        CASE
            WHEN j.status = 'assigned'    THEN 1
            WHEN j.status = 'in_progress' THEN 2
            WHEN j.status = 'open'        THEN 3
            WHEN j.status = 'closed'      THEN 4
            ELSE 5
        END,
        j.id DESC
    LIMIT 500
");
$stmt->execute([$companyId, $userId]);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| Payment by Month  (closed jobs only, newest month first)
|--------------------------------------------------------------------------
*/
$paymentMonths = [];
foreach ($jobs as $job) {
    if (($job['status'] ?? '') !== 'closed' || empty($job['closed_at'])) {
        continue;
    }
    $monthKey = date('Y-m', strtotime($job['closed_at']));
    $myShare  = jobShareAmount((float)$job['staff_fee'], (int)$job['assigned_staff_count']);

    if (!isset($paymentMonths[$monthKey])) {
        $paymentMonths[$monthKey] = ['jobs' => [], 'total' => 0];
    }
    $paymentMonths[$monthKey]['jobs'][]  = $job + ['my_share' => $myShare];
    $paymentMonths[$monthKey]['total']  += $myShare;
}
krsort($paymentMonths);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="format-detection" content="telephone=no">
    <title>Staff Dashboard - <?= esc($companyName) ?></title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }
        .topbar {
            background: #0f172a;
            color: #fff;
            padding: 14px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
        }
        .topbar .brand {
            font-weight: bold;
            font-size: 16px;
        }
        .topbar .right {
            display: flex;
            align-items: center;
            gap: 16px;
            font-size: 14px;
        }
        .topbar a.logout {
            color: #fca5a5;
            text-decoration: none;
            font-weight: bold;
        }
        .topbar a.logout:hover { color: #f87171; }

        .container {
            max-width: 1300px;
            margin: 24px auto;
            padding: 0 16px;
        }
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin: 4px 0 14px;
            padding: 9px 16px;
            background: #fff;
            border: 1px solid #dbe3ee;
            border-radius: 10px;
            color: #1f2937;
            font-weight: bold;
            text-decoration: none;
        }
        .back-link:hover { border-color: #bfdbfe; color: #1d4ed8; }
        .page-title { margin: 0 0 16px; font-size: 26px; }

        .box {
            background: #fff;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
            margin-bottom: 20px;
        }
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 16px;
        }
        .summary-card {
            background: #f8fafc;
            border-radius: 14px;
            padding: 18px;
        }
        .summary-label {
            font-size: 13px;
            color: #6b7280;
            margin-bottom: 8px;
        }
        .summary-value {
            font-size: 28px;
            font-weight: bold;
        }
        .muted { color: #6b7280; }

        .status {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: bold;
            white-space: nowrap;
        }
        .assigned { background: #dbeafe; color: #1d4ed8; }
        .in_progress { background: #fef3c7; color: #92400e; }
        .closed { background: #dcfce7; color: #166534; }
        .open { background: #e5e7eb; color: #374151; }

        .job-type-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: bold;
            background: #ede9fe;
            color: #6d28d9;
            margin-bottom: 6px;
        }

        .btn {
            display: inline-block;
            background: #0284c7;
            color: white;
            padding: 9px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 13px;
            font-weight: bold;
            border: none;
            cursor: pointer;
        }
        .btn:hover { background: #0369a1; }

        .btn-refresh { background: #16a34a; }
        .btn-refresh:hover { background: #15803d; }
        .btn-view { background: #0284c7; }
        .btn-view:hover { background: #0369a1; }
        .btn-close { background: #f59e0b; color: #161414; }
        .btn-close:hover { background: #d97706; }
        .btn-modify { background: #7c3aed; }
        .btn-modify:hover { background: #6d28d9; }

        .table-wrap {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .jobs-table {
            width: 100%;
            min-width: 1100px;
            border-collapse: collapse;
        }
        .jobs-table th,
        .jobs-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
            font-size: 14px;
            vertical-align: middle;
            white-space: nowrap;
            word-break: normal;
            overflow-wrap: normal;
        }
        .jobs-table th { background: #f8fafc; }
        .jobs-table td:nth-child(5),
        .jobs-table td:nth-child(6),
        .jobs-table td:nth-child(7),
        .jobs-table td:nth-child(8) {
            white-space: normal;
            word-break: break-word;
        }

        .section-head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        .month-payment-row {
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            margin-bottom: 10px;
            overflow: hidden;
            background: #fff;
        }
        .month-payment-summary {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            padding: 14px 16px;
            cursor: pointer;
            font-weight: bold;
            background: #f8fafc;
        }
        .month-payment-dots {
            font-size: 24px;
            line-height: 1;
            color: #374151;
        }
        .month-payment-details {
            display: none;
            padding: 12px;
        }
        .month-payment-row.open .month-payment-details { display: block; }

        @media (max-width: 900px) {
            .summary-grid { grid-template-columns: 1fr; }
            .container { padding: 0 10px; }
            .box { padding: 14px; border-radius: 12px; }
            .jobs-table { min-width: 980px; }
            .jobs-table th, .jobs-table td { font-size: 13px; padding: 10px 8px; }
            .btn { padding: 8px 10px; font-size: 12px; }
        }
        @media (max-width: 600px) {
            .summary-value { font-size: 22px; }
            .jobs-table { min-width: 900px; }
            .jobs-table th, .jobs-table td { font-size: 12px; padding: 8px 6px; }
            .status { font-size: 11px; padding: 5px 8px; }
        }
    </style>
</head>
<body>

    <div class="topbar">
        <div class="brand"><?= esc($companyName) ?> - Service Portal</div>
        <div class="right">
            <span>Welcome, <?= esc($staffName) ?></span>
            <a class="logout" href="../auth/logout.php">Logout</a>
        </div>
    </div>

    <div class="container">
        <a class="back-link" href="../customer/company_home.php" onclick="if(document.referrer){history.back();return false;}">&larr; Back to Dashboard</a>

        <h1 class="page-title">Staff Dashboard</h1>

        <div class="box">
            <h2>My Summary</h2>

            <div class="box">
                <h2>Payment by Month</h2>

                <?php if ($paymentMonths): ?>
                    <?php foreach ($paymentMonths as $monthKey => $month): ?>
                        <div class="month-payment-row">
                            <div class="month-payment-summary" onclick="this.parentElement.classList.toggle('open')">
                                <span><?= esc($monthKey) ?> - Total: <?= number_format($month['total'], 0) ?> LAK</span>
                                <span class="month-payment-dots">...</span>
                            </div>

                            <div class="month-payment-details">
                                <div class="table-wrap">
                                    <table class="jobs-table">
                                        <thead>
                                            <tr>
                                                <th>Job No</th>
                                                <th>Customer</th>
                                                <th>Issue</th>
                                                <th>Total Fee</th>
                                                <th>My Share</th>
                                                <th>Closed Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($month['jobs'] as $mjob): ?>
                                                <?php
                                                    $displayCustomer = ($mjob['customer_name'] ?? '') !== ''
                                                        ? $mjob['customer_name']
                                                        : ($mjob['sd_no'] ?: '');
                                                ?>
                                                <tr>
                                                    <td><?= esc(substr((string)$mjob['job_no'], 4, 10)) ?></td>
                                                    <td><?= esc($displayCustomer) ?></td>
                                                    <td><?= esc($mjob['issue_title']) ?></td>
                                                    <td><?= number_format((float)$mjob['staff_fee'], 0) ?> LAK</td>
                                                    <td><strong><?= number_format($mjob['my_share'], 0) ?> LAK</strong></td>
                                                    <td><?= esc(date('d/m/Y', strtotime($mjob['closed_at']))) ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="muted">No completed payment jobs yet.</p>
                <?php endif; ?>
            </div>

            <div class="summary-grid">
                <div class="summary-card">
                    <div class="summary-label">Total Jobs</div>
                    <div class="summary-value"><?= esc($summary['total_jobs'] ?? 0) ?></div>
                </div>

                <div class="summary-card">
                    <div class="summary-label">Completed Jobs</div>
                    <div class="summary-value"><?= esc($summary['total_closed_jobs'] ?? 0) ?></div>
                </div>

                <div class="summary-card">
                    <div class="summary-label">Incomplete Jobs</div>
                    <div class="summary-value"><?= esc($summary['total_incomplete_jobs'] ?? 0) ?></div>
                </div>

                <div class="summary-card">
                    <div class="summary-label">Total Earned</div>
                    <div class="summary-value"><?= number_format($summary['total_earned'] ?? 0, 0) ?> LAK</div>
                </div>
            </div>
        </div>

        <div class="box">
            <div class="section-head">
                <div>
                    <h2 style="margin:0;">My Jobs</h2>
                    <p class="muted" style="margin:6px 0 0;">Each job fee is split evenly among all assigned technicians.</p>
                </div>

                <a class="btn btn-refresh" href="sp_jobs_staff.php">Refresh</a>
            </div>

            <div class="table-wrap">
                <table class="jobs-table">
                    <thead>
                        <tr>
                            <th width="130">Action</th>
                            <th>Status</th>
                            <th>Job No</th>
                            <th>Type</th>
                            <th>Customer</th>
                            <th>Machine</th>
                            <th>Issue</th>
                            <th>Total Fee</th>
                            <th>My Share</th>
                            <th>Staff Count</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($jobs): ?>
                            <?php $totalMyShare = 0; ?>
                            <?php foreach ($jobs as $job): ?>
                                <?php
                                    $myShare = jobShareAmount((float)$job['staff_fee'], (int)$job['assigned_staff_count']);
                                    if (($job['status'] ?? '') === 'closed') {
                                        $totalMyShare += $myShare;
                                    }
                                    $isClosed = (($job['status'] ?? '') === 'closed');
                                    $displayCustomer = ($job['customer_name'] ?? '') !== ''
                                        ? $job['customer_name']
                                        : ($job['sd_no'] ?: '-');
                                ?>
                                <tr>
                                    <td>
                                        <a class="btn btn-view" href="sp_job_view.php?id=<?= (int)$job['id'] ?>">View</a>
                                        <?php if (!$isClosed): ?>
                                            <a class="btn btn-close" href="sp_job_close.php?id=<?= (int)$job['id'] ?>">Close</a>
                                        <?php else: ?>
                                            <a class="btn btn-modify" href="sp_job_close.php?id=<?= (int)$job['id'] ?>">Modify</a>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <span class="status <?= esc($job['status']) ?>">
                                            <?= esc(ucwords(str_replace('_', ' ', (string)$job['status']))) ?>
                                        </span>
                                    </td>

                                    <td><?= esc(substr((string)$job['job_no'], 4, 10)) ?></td>

                                    <td>
                                        <span class="job-type-badge">
                                            <?= esc(paymentTypeLabel($job['payment_type'] ?? '', $paymentTypeMap)) ?>
                                        </span>
                                    </td>

                                    <td><?= esc($displayCustomer) ?></td>

                                    <td>
                                        <?php if (($job['unique_machine_no'] ?? '') !== '' || ($job['machine_no'] ?? '') !== ''): ?>
                                            <strong><?= esc($job['unique_machine_no'] ?: $job['machine_no']) ?></strong><br>
                                            <span class="muted"><?= esc($job['machine_model'] ?? '') ?></span>
                                        <?php else: ?>
                                            <span class="muted">-</span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <strong><?= esc($job['issue_title']) ?></strong><br>
                                        <span class="muted"><?= esc($job['issue_description'] ?? '') ?></span>
                                    </td>

                                    <td><?= number_format((float)$job['staff_fee'], 0) ?> LAK</td>

                                    <td><strong><?= number_format($myShare, 0) ?> LAK</strong></td>

                                    <td><?= esc($job['assigned_staff_count']) ?></td>
                                </tr>
                            <?php endforeach; ?>

                            <tr style="background:#f8fafc; font-weight:bold;">
                                <td colspan="8" style="text-align:right;">Total Earned:</td>
                                <td><strong><?= number_format($totalMyShare, 0) ?> LAK</strong></td>
                                <td></td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="10">No assigned jobs yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

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