<?php
// Business logic (including any header('Location: ...') redirects after a POST action)
// must run before includes/header.php, since that include emits HTML immediately and
// would make any later redirect fail silently ("headers already sent"), leaving the
// page blank after actions like creating/editing/deleting/paying a pay run.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/_module.php';
require_once __DIR__ . '/../../classes/User.php';

$database = new Database();
$conn     = $database->getConnection();
$auth     = new Auth($conn);

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $deleteId       = (int)($_POST['run_id'] ?? 0);
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if ($deleteId <= 0) {
            $error = 'Invalid pay run ID.';
        } elseif ($confirmPassword === '') {
            $error = 'Please enter your password to confirm deletion.';
        } else {
            $userModel   = new User($conn);
            $currentUser = $userModel->getUserById((int)$_SESSION['user_id']);
            if (!$currentUser || !password_verify($confirmPassword, $currentUser['password'])) {
                $error = 'Incorrect password. Pay run was not deleted.';
            } elseif ($payroll->deletePayRun($deleteId)) {
                header('Location: pay_runs.php?deleted=1');
                exit();
            } else {
                $error = 'Failed to delete payroll run.';
            }
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'edit') {
        $editId = (int)($_POST['run_id'] ?? 0);
        if ($editId <= 0) {
            $error = 'Invalid pay run ID.';
        } else {
            $editData = [
                'run_number'       => trim($_POST['run_number'] ?? ''),
                'pay_period_start' => trim($_POST['pay_period_start'] ?? ''),
                'pay_period_end'   => trim($_POST['pay_period_end'] ?? ''),
                'pay_date'         => trim($_POST['pay_date'] ?? ''),
                'currency_code'    => trim($_POST['currency_code'] ?? 'MWK'),
                'notes'            => trim($_POST['notes'] ?? ''),
            ];
            if ($editData['run_number'] === '' || $editData['pay_period_start'] === '' || $editData['pay_period_end'] === '' || $editData['pay_date'] === '') {
                $error = 'Run number, period dates, and pay date are required.';
            } elseif ($payroll->updatePayRun($editId, $editData)) {
                header('Location: pay_runs.php?updated=1');
                exit();
            } else {
                $error = 'Failed to update pay run. Paid runs cannot be edited.';
            }
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'pay') {
        $payId = (int)($_POST['run_id'] ?? 0);
        if ($payId > 0) {
            $result = $payroll->markAsPaid($payId, (int)$_SESSION['user_id']);
            if ($result['ok']) {
                header('Location: pay_runs.php?paid=1');
                exit();
            } else {
                $error = $result['error'] ?? 'Failed to mark pay run as paid.';
            }
        } else {
            $error = 'Invalid pay run ID.';
        }
    } elseif (!$payroll->tableExists('payroll_runs')) {
        $error = 'Payroll run tables are not installed yet.';
    } elseif ($payroll->createPayRun($_POST, $_SESSION['user_id'])) {
        header('Location: pay_runs.php');
        exit();
    } else {
        $error = 'Failed to create payroll run.';
    }
}

include '../../includes/header.php';

$runs = $payroll->getPayRuns();

payrollModuleStyles();
?>

<div class="container-fluid px-4">
    <?php payrollModuleNav('pay_runs'); ?>

    <div class="payroll-page-head">
        <div>
            <h1>Pay Runs</h1>
            <p>Prepare, review, approve, and archive payroll periods with audit-ready totals.</p>
        </div>
        <a href="../dashboard/admin.php" class="btn btn-outline-secondary no-print"><i class="fas fa-arrow-left"></i> Admin Dashboard</a>
    </div>

    <?php payrollMigrationNotice($payroll, ['payroll_runs', 'payroll_payslips'], 'Pay runs require the professional payroll tables.'); ?>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    <?php if (isset($_GET['updated'])): ?>
        <div class="alert alert-success">Pay run updated successfully.</div>
    <?php endif; ?>
    <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-success">Pay run deleted successfully.</div>
    <?php endif; ?>
    <?php if (isset($_GET['paid'])): ?>
        <div class="alert alert-success">Pay run marked as paid. Salary expenses have been recorded to each branch.</div>
    <?php endif; ?>

    <div class="row g-3">
        <div class="col-lg-4">
            <div class="payroll-panel">
                <div class="payroll-panel-title"><h2>Create Draft Pay Run</h2></div>
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label" for="run_number">Run Number</label>
                        <input type="text" class="form-control" id="run_number" name="run_number" placeholder="PAY-2026-06">
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="pay_period_start">Period Start</label>
                        <input type="date" class="form-control" id="pay_period_start" name="pay_period_start" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="pay_period_end">Period End</label>
                        <input type="date" class="form-control" id="pay_period_end" name="pay_period_end" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="pay_date">Pay Date</label>
                        <input type="date" class="form-control" id="pay_date" name="pay_date" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="currency_code">Currency</label>
                        <input type="text" class="form-control" id="currency_code" name="currency_code" value="MWK" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="notes">Notes</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary" <?php echo $payroll->tableExists('payroll_runs') ? '' : 'disabled'; ?>><i class="fas fa-save"></i> Create Pay Run</button>
                </form>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="payroll-panel">
                <div class="payroll-panel-title">
                    <h2>Payroll Periods</h2>
                    <button type="button" class="btn btn-outline-secondary btn-sm no-print" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered payroll-table">
                        <thead>
                            <tr>
                                <th>Run</th>
                                <th>Period</th>
                                <th>Pay Date</th>
                                <th>Gross</th>
                                <th>Deductions</th>
                                <th>Net</th>
                                <th>Status</th>
                                <th class="no-print">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($runs)): ?>
                                <?php foreach ($runs as $run): ?>
                                    <tr>
                                        <td><?php echo payrollText($run['run_number']); ?></td>
                                        <td><?php echo payrollText($run['pay_period_start']); ?> to <?php echo payrollText($run['pay_period_end']); ?></td>
                                        <td><?php echo payrollText($run['pay_date']); ?></td>
                                        <td><?php echo payrollMoney($run['gross_pay'] ?? 0); ?></td>
                                        <td><?php echo payrollMoney($run['total_deductions'] ?? 0); ?></td>
                                        <td><?php echo payrollMoney($run['net_pay'] ?? 0); ?></td>
                                        <td><?php echo payrollStatusBadge($run['status'] ?? 'draft'); ?></td>
                                        <td class="no-print" style="white-space:nowrap;">
                                            <button type="button" class="btn btn-sm btn-primary view-run-btn me-1"
                                                data-bs-toggle="modal" data-bs-target="#viewRunModal"
                                                data-run-id="<?php echo (int)$run['payroll_run_id']; ?>"
                                                data-run-number="<?php echo htmlspecialchars($run['run_number'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-start="<?php echo htmlspecialchars($run['pay_period_start'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-end="<?php echo htmlspecialchars($run['pay_period_end'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-pay-date="<?php echo htmlspecialchars($run['pay_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-currency="<?php echo htmlspecialchars($run['currency_code'] ?? 'MWK', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-status="<?php echo htmlspecialchars($run['status'] ?? 'draft', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-gross="<?php echo htmlspecialchars($run['gross_pay'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-deductions="<?php echo htmlspecialchars($run['total_deductions'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-net="<?php echo htmlspecialchars($run['net_pay'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-notes="<?php echo htmlspecialchars($run['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-created="<?php echo htmlspecialchars($run['created_at'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                                <i class="fas fa-eye"></i> View
                                            </button>
                                            <a href="payslips.php?run_id=<?php echo (int)$run['payroll_run_id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                                                <i class="fas fa-receipt"></i> Payslips
                                            </a>
                                            <?php if (($run['status'] ?? 'draft') !== 'paid'): ?>
                                            <button type="button" class="btn btn-sm btn-warning edit-run-btn me-1"
                                                data-bs-toggle="modal" data-bs-target="#editRunModal"
                                                data-run-id="<?php echo (int)$run['payroll_run_id']; ?>"
                                                data-run-number="<?php echo htmlspecialchars($run['run_number'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-start="<?php echo htmlspecialchars($run['pay_period_start'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-end="<?php echo htmlspecialchars($run['pay_period_end'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-pay-date="<?php echo htmlspecialchars($run['pay_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-currency="<?php echo htmlspecialchars($run['currency_code'] ?? 'MWK', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-notes="<?php echo htmlspecialchars($run['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button type="button" class="btn btn-sm btn-success pay-run-btn me-1"
                                                data-bs-toggle="modal" data-bs-target="#payRunModal"
                                                data-run-id="<?php echo (int)$run['payroll_run_id']; ?>"
                                                data-run-number="<?php echo htmlspecialchars($run['run_number'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-net="<?php echo htmlspecialchars($run['net_pay'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-currency="<?php echo htmlspecialchars($run['currency_code'] ?? 'MWK', ENT_QUOTES, 'UTF-8'); ?>">
                                                <i class="fas fa-money-bill-wave"></i> Pay
                                            </button>
                                            <?php endif; ?>
                                            <button type="button" class="btn btn-sm btn-danger delete-run-btn"
                                                data-bs-toggle="modal" data-bs-target="#deleteRunModal"
                                                data-run-id="<?php echo (int)$run['payroll_run_id']; ?>"
                                                data-run-number="<?php echo htmlspecialchars($run['run_number'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-start="<?php echo htmlspecialchars($run['pay_period_start'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-period-end="<?php echo htmlspecialchars($run['pay_period_end'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-pay-date="<?php echo htmlspecialchars($run['pay_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-currency="<?php echo htmlspecialchars($run['currency_code'] ?? 'MWK', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-status="<?php echo htmlspecialchars($run['status'] ?? 'draft', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-gross="<?php echo htmlspecialchars($run['gross_pay'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-deductions="<?php echo htmlspecialchars($run['total_deductions'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-net="<?php echo htmlspecialchars($run['net_pay'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>"
                                                data-notes="<?php echo htmlspecialchars($run['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="8" class="text-center">No payroll runs found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <?php payrollModuleEnd(); ?>
</div>

<!-- View Pay Run Modal -->
<div class="modal fade" id="viewRunModal" tabindex="-1" aria-labelledby="viewRunModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewRunModalLabel"><i class="fas fa-file-invoice-dollar me-2"></i>Pay Run Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">

                <div class="d-flex justify-content-between align-items-start mb-3">
                    <div>
                        <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Run Reference</div>
                        <div class="fw-bold fs-5" id="vr-run-number">—</div>
                    </div>
                    <span id="vr-status-badge"></span>
                </div>

                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <div class="border rounded p-2">
                            <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Pay Period</div>
                            <div class="fw-semibold" id="vr-period">—</div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="border rounded p-2">
                            <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Pay Date</div>
                            <div class="fw-semibold" id="vr-pay-date">—</div>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="border rounded p-2">
                            <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Currency</div>
                            <div class="fw-semibold" id="vr-currency">—</div>
                        </div>
                    </div>
                </div>

                <table class="table table-sm table-bordered mb-3">
                    <tbody>
                        <tr>
                            <td class="text-muted">Gross Pay</td>
                            <td class="text-end fw-semibold" id="vr-gross">—</td>
                        </tr>
                        <tr>
                            <td class="text-muted">Total Deductions</td>
                            <td class="text-end fw-semibold" id="vr-deductions">—</td>
                        </tr>
                        <tr class="table-dark">
                            <td class="fw-bold">Net Pay</td>
                            <td class="text-end fw-bold" id="vr-net">—</td>
                        </tr>
                    </tbody>
                </table>

                <div id="vr-notes-row" class="mb-2" style="display:none;">
                    <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Notes</div>
                    <div id="vr-notes" class="border rounded p-2 bg-light" style="font-size:13px;"></div>
                </div>

                <div class="text-muted" style="font-size:11px;" id="vr-created">Created: —</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <a href="payslips.php" id="vr-payslips-link" class="btn btn-primary"><i class="fas fa-receipt"></i> View Payslips</a>
            </div>
        </div>
    </div>
</div>

<!-- Pay Confirmation Modal -->
<div class="modal fade" id="payRunModal" tabindex="-1" aria-labelledby="payRunModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="payRunModalLabel"><i class="fas fa-money-bill-wave text-success me-2"></i>Confirm Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>You are about to mark pay run <strong id="pay-run-label"></strong> as <strong class="text-success">Paid</strong>.</p>
                <div class="alert alert-info mb-2" style="font-size:13px;">
                    <i class="fas fa-info-circle me-1"></i>
                    Total net pay of <strong id="pay-run-net"></strong> will be recorded as a <strong>Salaries</strong> expense split by branch.
                    All linked payslips will be marked as paid.
                </div>
                <p class="text-muted mb-0" style="font-size:13px;">This action cannot be undone. Are you sure you want to continue?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <form method="POST" id="pay-run-form" style="display:inline;">
                    <input type="hidden" name="action" value="pay">
                    <input type="hidden" name="run_id" id="pay-run-id" value="">
                    <button type="submit" class="btn btn-success"><i class="fas fa-check me-1"></i> Yes, Mark as Paid</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Edit Pay Run Modal -->
<div class="modal fade" id="editRunModal" tabindex="-1" aria-labelledby="editRunModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editRunModalLabel"><i class="fas fa-edit me-2"></i>Edit Pay Run</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="edit-run-form">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="run_id" id="edit-run-id" value="">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label" for="edit-run-number">Run Number</label>
                        <input type="text" class="form-control" id="edit-run-number" name="run_number" required>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label" for="edit-period-start">Period Start</label>
                            <input type="date" class="form-control" id="edit-period-start" name="pay_period_start" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label" for="edit-period-end">Period End</label>
                            <input type="date" class="form-control" id="edit-period-end" name="pay_period_end" required>
                        </div>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label" for="edit-pay-date">Pay Date</label>
                            <input type="date" class="form-control" id="edit-pay-date" name="pay_date" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label" for="edit-currency">Currency</label>
                            <input type="text" class="form-control" id="edit-currency" name="currency_code" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="edit-notes">Notes</label>
                        <textarea class="form-control" id="edit-notes" name="notes" rows="3"></textarea>
                    </div>
                    <div class="alert alert-warning mb-0" style="font-size:13px;">
                        <i class="fas fa-info-circle me-1"></i>
                        Editing does not recalculate payslips. To update payroll figures, delete this run and create a new one.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i> Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteRunModal" tabindex="-1" aria-labelledby="deleteRunModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteRunModalLabel"><i class="fas fa-triangle-exclamation me-2"></i>Delete Pay Run</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="delete-run-form">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="run_id" id="delete-run-id" value="">
                <div class="modal-body">

                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Pay Run</div>
                            <div class="fw-bold fs-5" id="dr-run-number">—</div>
                        </div>
                        <span id="dr-status-badge"></span>
                    </div>

                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <div class="border rounded p-2">
                                <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Pay Period</div>
                                <div class="fw-semibold" id="dr-period">—</div>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="border rounded p-2">
                                <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Pay Date</div>
                                <div class="fw-semibold" id="dr-pay-date">—</div>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="border rounded p-2">
                                <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Currency</div>
                                <div class="fw-semibold" id="dr-currency">—</div>
                            </div>
                        </div>
                    </div>

                    <table class="table table-sm table-bordered mb-3">
                        <tbody>
                            <tr>
                                <td class="text-muted">Gross Pay</td>
                                <td class="text-end fw-semibold" id="dr-gross">—</td>
                            </tr>
                            <tr>
                                <td class="text-muted">Total Deductions</td>
                                <td class="text-end fw-semibold" id="dr-deductions">—</td>
                            </tr>
                            <tr class="table-dark">
                                <td class="fw-bold">Net Pay</td>
                                <td class="text-end fw-bold" id="dr-net">—</td>
                            </tr>
                        </tbody>
                    </table>

                    <div id="dr-notes-row" class="mb-3" style="display:none;">
                        <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.06em;">Notes</div>
                        <div id="dr-notes" class="border rounded p-2 bg-light" style="font-size:13px;"></div>
                    </div>

                    <div class="alert alert-danger mb-3" style="font-size:13px;">
                        <i class="fas fa-exclamation-circle me-1"></i>
                        This will permanently delete the pay run and all linked payslips. This action cannot be undone.
                    </div>

                    <div class="mb-0">
                        <label class="form-label fw-semibold" for="delete-password">Enter your password to confirm</label>
                        <input type="password" class="form-control" id="delete-password" name="confirm_password" placeholder="Your account password" required autocomplete="current-password">
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-trash me-1"></i> Delete Pay Run</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
(function () {
    function fmtMoney(amount, cur) {
        return (cur || 'MWK') + ' ' + parseFloat(amount || 0).toLocaleString('en-MW', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    function fmtDate(s) {
        if (!s) return '—';
        var p = s.split('-');
        if (p.length === 3) {
            var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            return p[2] + ' ' + m[parseInt(p[1], 10) - 1] + ' ' + p[0];
        }
        return s;
    }

    var viewModalEl = document.getElementById('viewRunModal');
    if (viewModalEl) {
        viewModalEl.addEventListener('show.bs.modal', function (event) {
            var btn = event.relatedTarget;
            if (!btn) return;

            var runId  = btn.getAttribute('data-run-id');
            var cur    = btn.getAttribute('data-currency') || 'MWK';
            var status = (btn.getAttribute('data-status') || 'draft').toLowerCase();
            var notes  = btn.getAttribute('data-notes') || '';

            var statusColors = {approved: 'bg-success', active: 'bg-success', pending: 'bg-warning text-dark', closed: 'bg-info text-dark', paid: 'bg-info text-dark', draft: 'bg-secondary'};
            var badgeClass = statusColors[status] || 'bg-secondary';

            document.getElementById('vr-run-number').textContent = btn.getAttribute('data-run-number') || '—';
            document.getElementById('vr-status-badge').innerHTML = '<span class="badge ' + badgeClass + ' fs-6">' + status.toUpperCase() + '</span>';
            document.getElementById('vr-period').textContent = fmtDate(btn.getAttribute('data-period-start')) + ' – ' + fmtDate(btn.getAttribute('data-period-end'));
            document.getElementById('vr-pay-date').textContent = fmtDate(btn.getAttribute('data-pay-date'));
            document.getElementById('vr-currency').textContent = cur;
            document.getElementById('vr-gross').textContent = fmtMoney(btn.getAttribute('data-gross'), cur);
            document.getElementById('vr-deductions').textContent = fmtMoney(btn.getAttribute('data-deductions'), cur);
            document.getElementById('vr-net').textContent = fmtMoney(btn.getAttribute('data-net'), cur);
            document.getElementById('vr-created').textContent = 'Created: ' + (btn.getAttribute('data-created') || '—');

            var notesRow = document.getElementById('vr-notes-row');
            if (notes.trim()) {
                document.getElementById('vr-notes').textContent = notes;
                notesRow.style.display = '';
            } else {
                notesRow.style.display = 'none';
            }

            document.getElementById('vr-payslips-link').href = 'payslips.php?run_id=' + runId;
        });
    }

    var editModalEl = document.getElementById('editRunModal');
    if (editModalEl) {
        editModalEl.addEventListener('show.bs.modal', function (event) {
            var btn = event.relatedTarget;
            if (!btn) return;
            document.getElementById('edit-run-id').value        = btn.getAttribute('data-run-id');
            document.getElementById('edit-run-number').value    = btn.getAttribute('data-run-number') || '';
            document.getElementById('edit-period-start').value  = btn.getAttribute('data-period-start') || '';
            document.getElementById('edit-period-end').value    = btn.getAttribute('data-period-end') || '';
            document.getElementById('edit-pay-date').value      = btn.getAttribute('data-pay-date') || '';
            document.getElementById('edit-currency').value      = btn.getAttribute('data-currency') || 'MWK';
            document.getElementById('edit-notes').value         = btn.getAttribute('data-notes') || '';
        });
    }

    var deleteModalEl = document.getElementById('deleteRunModal');
    if (deleteModalEl) {
        deleteModalEl.addEventListener('show.bs.modal', function (event) {
            var btn = event.relatedTarget;
            if (!btn) return;

            var cur    = btn.getAttribute('data-currency') || 'MWK';
            var status = (btn.getAttribute('data-status') || 'draft').toLowerCase();
            var notes  = btn.getAttribute('data-notes') || '';

            var statusColors = {approved: 'bg-success', active: 'bg-success', pending: 'bg-warning text-dark', closed: 'bg-info text-dark', paid: 'bg-info text-dark', draft: 'bg-secondary'};
            var badgeClass = statusColors[status] || 'bg-secondary';

            document.getElementById('delete-run-id').value = btn.getAttribute('data-run-id');
            document.getElementById('delete-password').value = '';
            document.getElementById('dr-run-number').textContent    = btn.getAttribute('data-run-number') || '—';
            document.getElementById('dr-status-badge').innerHTML    = '<span class="badge ' + badgeClass + ' fs-6">' + status.toUpperCase() + '</span>';
            document.getElementById('dr-period').textContent        = fmtDate(btn.getAttribute('data-period-start')) + ' – ' + fmtDate(btn.getAttribute('data-period-end'));
            document.getElementById('dr-pay-date').textContent      = fmtDate(btn.getAttribute('data-pay-date'));
            document.getElementById('dr-currency').textContent      = cur;
            document.getElementById('dr-gross').textContent         = fmtMoney(btn.getAttribute('data-gross'), cur);
            document.getElementById('dr-deductions').textContent    = fmtMoney(btn.getAttribute('data-deductions'), cur);
            document.getElementById('dr-net').textContent           = fmtMoney(btn.getAttribute('data-net'), cur);

            var notesRow = document.getElementById('dr-notes-row');
            if (notes.trim()) {
                document.getElementById('dr-notes').textContent = notes;
                notesRow.style.display = '';
            } else {
                notesRow.style.display = 'none';
            }
        });

        deleteModalEl.addEventListener('hidden.bs.modal', function () {
            document.getElementById('delete-password').value = '';
        });
    }

    var payModalEl = document.getElementById('payRunModal');
    if (payModalEl) {
        payModalEl.addEventListener('show.bs.modal', function (event) {
            var btn = event.relatedTarget;
            if (!btn) return;
            var cur = btn.getAttribute('data-currency') || 'MWK';
            var net = parseFloat(btn.getAttribute('data-net') || 0).toLocaleString('en-MW', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('pay-run-id').value = btn.getAttribute('data-run-id');
            document.getElementById('pay-run-label').textContent = btn.getAttribute('data-run-number') || '—';
            document.getElementById('pay-run-net').textContent = cur + ' ' + net;
        });
    }
})();
</script>

<?php include '../../includes/footer.php'; ?>
