<?php
require_once 'db.php';
requireStaff();
function formatJobNo($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;
}

$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

function paymentTypeLabel($paymentType)
{
    $labels = [
        'fix_normal' => 'Fix normal problem',
        'meter_toner_bill' => 'Meter / Toner',
        'change_part' => 'Change Part',
        'other' => 'Other'
    ];

    return $labels[$paymentType] ?? 'Other';
}

/*
|--------------------------------------------------------------------------
| Staff Summary
|--------------------------------------------------------------------------
*/
$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 job_staff_assignments jsa2
                            WHERE jsa2.job_id = j.id
                        ), 0),
                    0)
                ELSE 0
            END
        ), 0) AS total_earned
    FROM jobs j
    INNER JOIN job_staff_assignments jsa ON j.id = jsa.job_id
    WHERE jsa.staff_id = ?
");
$summaryStmt->execute([$_SESSION['staff_id']]);
$summary = $summaryStmt->fetch();

/*
|--------------------------------------------------------------------------
| Staff Job List
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT
        j.*,
        c.customer_name AS normal_customer_name,
        m.unique_machine_no,
        m.machine_model,
        m.serial_no,
        m.customer_name AS machine_customer_name,
        m.location_text,
        m.main_email,
        m.invoice_email,
        m.cc_email,
        m.telephone,
        (
            SELECT COUNT(*)
            FROM job_staff_assignments jsa2
            WHERE jsa2.job_id = j.id
        ) AS assigned_staff_count
    FROM jobs j
    INNER JOIN job_staff_assignments jsa ON j.id = jsa.job_id
    LEFT JOIN customers c ON j.customer_id = c.id
    LEFT JOIN machines m ON j.machine_id = m.id
    WHERE jsa.staff_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
");
$stmt->execute([$_SESSION['staff_id']]);
$jobs = $stmt->fetchAll();

$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);

function jobShareAmount($staffFee, $assignedCount)
{
    if ((int)$assignedCount <= 0) {
        return 0;
    }
    return round($staffFee / $assignedCount);
}
?>
<!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 - Service Portal</title>

    <link rel="stylesheet" href="css/style.css?v=1">
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            color: #111827;
        }
        .container {
            max-width: 1300px;
            margin: 24px auto;
            padding: 0 16px;
        }
        .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;
        }
        .success-message {
            background: #dcfce7;
            color: #166534;
            padding: 12px 14px;
            border-radius: 10px;
            margin-bottom: 16px;
            font-weight: bold;
        }
        .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;
        }

        .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;       /* prevent letters going vertical */
    word-break: normal;        /* stop breaking every letter */
    overflow-wrap: normal;
}

.jobs-table th {
    background: #f8fafc;
}

/* allow only long text columns to wrap */
.jobs-table td:nth-child(5),  /* Customer */
.jobs-table td:nth-child(6),  /* Machine */
.jobs-table td:nth-child(7),  /* Location */
.jobs-table td:nth-child(8) { /* Issue */
    white-space: normal;
    word-break: break-word;
}

/* center small columns */
.jobs-table th:nth-child(1),
.jobs-table td:nth-child(1),
.jobs-table th:nth-child(9),
.jobs-table td:nth-child(9),
.jobs-table th:nth-child(10),
.jobs-table td:nth-child(10),
.jobs-table th:nth-child(11),
.jobs-table td:nth-child(11) {
    text-align: center;
}

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

        .btn-update {
                background: #0284c7; /* blue */
                color: #fff;
            }

            .btn-update:hover {
                background: #0369a1;
            }

            .btn-modify {
                background: #f59e0b; /* orange */
                color: #161414;
            }

            .btn-modify:hover {
                background: #d97706;
            }
            .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;
            }
        }
        @media (max-width: 1024px) {
    .jobs-table td:nth-child(8),
    .jobs-table th:nth-child(8) {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 300px;
    }
}
    </style>
</head>
<body>

    <?php include 'header.php'; ?>

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

        <?php if ($success_message): ?>
            <div class="success-message"><?= esc($success_message) ?></div>
        <?php endif; ?>

        <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 $job): ?>
                                    <?php
                                        $isMachineJob = (($job['job_type'] ?? '') === 'machine');
                                        $displayCustomer = $isMachineJob
                                            ? ($job['machine_customer_name'] ?? '')
                                            : ($job['normal_customer_name'] ?? '');
                                    ?>
                                    <tr>
                                        <td><?= esc(substr($job['job_no'], 4, 10)) ?></td>
                                        <td><?= esc($displayCustomer) ?></td>
                                        <td><?= esc($job['issue_title']) ?></td>
                                        <td><?= number_format((float)$job['staff_fee'], 0) ?> LAK</td>
                                        <td><strong><?= number_format($job['my_share'], 0) ?> LAK</strong></td>
                                        <td><?= esc(date('d/m/Y', strtotime($job['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="staff-dashboard.php">Refresh</a>
            </div>

            <div class="table-wrap">
                <table class="jobs-table">
                    <thead>
                        <tr>
                            <th width="75">Action</th>
                            <th>Status</th>
                            <th>Job No</th>
                            <th>Type</th>
                            <th>Customer</th>
                            <th>Machine</th>
                            <th>Location</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;
                                    }

                                    $isMachineJob = (($job['job_type'] ?? '') === 'machine');

                                    $displayCustomer = $isMachineJob
                                        ? ($job['machine_customer_name'] ?? '')
                                        : ($job['normal_customer_name'] ?? '');

                                    $displayLocation = $isMachineJob
                                        ? ($job['location_text'] ?? '')
                                        : '-';
                                ?>
                                <tr>
                                    <td>
                                        <a 
                                            class="btn <?= $job['status'] === 'closed' ? 'btn-modify' : 'btn-update' ?>" 
                                            href="close_job.php?id=<?= (int)$job['id'] ?>"
                                        >
                                            <?= $job['status'] === 'closed' ? 'Modify' : 'Update' ?>
                                        </a>
                                    </td>

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

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

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

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

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

                                    <td><?= esc($displayLocation) ?></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="9" style="text-align:right;">Total Earned:</td>
                                <td><strong><?= number_format($totalMyShare, 0) ?> LAK</strong></td>
                                <td colspan="3"></td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="11">No assigned jobs yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</body>
</html>