<?php
include '../../includes/header.php';
require_once __DIR__ . '/_module.php';

payrollRequireAdmin($auth);

$payroll   = new Payroll($conn);
$employees = $payroll->getAllEmployees();
$payRuns   = $payroll->getPayRuns();

$error = '';
$filterStatus = $_GET['status'] ?? '';
$filterType   = $_GET['type'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $data = [
            'employee_id'    => (int)($_POST['employee_id'] ?? 0),
            'deduction_type' => $_POST['deduction_type'] ?? 'Other',
            'description'    => trim($_POST['description'] ?? ''),
            'amount'         => (float)($_POST['amount'] ?? 0),
            'incident_date'  => trim($_POST['incident_date'] ?? ''),
            'payroll_run_id' => (int)($_POST['payroll_run_id'] ?? 0) ?: null,
        ];
        if ($data['employee_id'] <= 0 || $data['description'] === '' || $data['amount'] <= 0) {
            $error = 'Employee, description, and a valid amount are required.';
        } else {
            $id = $payroll->saveEmployeeDeduction($data, (int)$_SESSION['user_id']);
            if ($id) {
                header('Location: other_deductions.php?added=1');
                exit();
            } else {
                $error = 'Failed to record deduction. Run the database migration first.';
            }
        }
    } elseif ($action === 'apply') {
        $id = (int)($_POST['ded_id'] ?? 0);
        if ($id > 0 && $payroll->updateEmployeeDeductionStatus($id, 'applied')) {
            header('Location: other_deductions.php?applied=1');
            exit();
        }
    } elseif ($action === 'cancel') {
        $id = (int)($_POST['ded_id'] ?? 0);
        if ($id > 0 && $payroll->updateEmployeeDeductionStatus($id, 'cancelled')) {
            header('Location: other_deductions.php?cancelled=1');
            exit();
        }
    } elseif ($action === 'delete') {
        $id = (int)($_POST['ded_id'] ?? 0);
        if ($id > 0 && $payroll->deleteEmployeeDeduction($id)) {
            header('Location: other_deductions.php?deleted=1');
            exit();
        } else {
            $error = 'Could not delete — only pending deductions can be removed.';
        }
    }
}

$filters = [];
if ($filterStatus) $filters['status']         = $filterStatus;
if ($filterType)   $filters['deduction_type'] = $filterType;
$deductions = $payroll->getEmployeeDeductions($filters);
$summary    = $payroll->getEmployeeDeductionSummary();

payrollModuleStyles();
?>

<?php if (isset($_GET['added'])): ?>
<div class="alert alert-success alert-dismissible fade show mx-4 mt-3" role="alert">
    Deduction recorded. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (isset($_GET['applied'])): ?>
<div class="alert alert-success alert-dismissible fade show mx-4 mt-3" role="alert">
    Deduction marked as applied. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (isset($_GET['cancelled'])): ?>
<div class="alert alert-secondary alert-dismissible fade show mx-4 mt-3" role="alert">
    Deduction cancelled. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (isset($_GET['deleted'])): ?>
<div class="alert alert-info alert-dismissible fade show mx-4 mt-3" role="alert">
    Deduction deleted. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

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

    <div class="payroll-page-head">
        <div>
            <h1>Other Deductions</h1>
            <p>Record and track damages, missing items, penalties, and other employee-level deductions.</p>
        </div>
        <div class="no-print">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDeductionModal">
                <i class="fas fa-plus"></i> Add Deduction
            </button>
        </div>
    </div>

    <?php payrollMigrationNotice($payroll, ['payroll_employee_deductions'], 'Run database_migrations/payroll_employee_deductions.sql to enable other deductions tracking.'); ?>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="payroll-metrics">
        <div class="payroll-metric">
            <strong>Pending</strong>
            <span><?php echo number_format($summary['pending_count']); ?></span>
        </div>
        <div class="payroll-metric">
            <strong>Pending Amount</strong>
            <span><?php echo payrollMoney($summary['pending_total']); ?></span>
        </div>
        <div class="payroll-metric">
            <strong>Total Applied</strong>
            <span><?php echo payrollMoney($summary['applied_total']); ?></span>
        </div>
    </div>

    <!-- Filters -->
    <form method="GET" class="payroll-panel mb-3 no-print">
        <div class="row g-2 align-items-end">
            <div class="col-auto">
                <label class="form-label mb-1">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['pending' => 'Pending', 'applied' => 'Applied', 'cancelled' => 'Cancelled'] as $v => $l): ?>
                        <option value="<?php echo $v; ?>"<?php echo $filterStatus === $v ? ' selected' : ''; ?>><?php echo $l; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <label class="form-label mb-1">Type</label>
                <select name="type" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['Damages', 'Missing', 'Penalty', 'Other'] as $t): ?>
                        <option value="<?php echo $t; ?>"<?php echo $filterType === $t ? ' selected' : ''; ?>><?php echo $t; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-sm btn-outline-secondary">Filter</button>
                <a href="other_deductions.php" class="btn btn-sm btn-link">Clear</a>
            </div>
        </div>
    </form>

    <div class="payroll-panel">
        <div class="payroll-panel-title">
            <h2>Deductions</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>Employee</th>
                        <th>Type</th>
                        <th>Description</th>
                        <th>Incident Date</th>
                        <th>Amount</th>
                        <th>Pay Run</th>
                        <th>Status</th>
                        <th class="no-print">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($deductions)): ?>
                        <tr><td colspan="8" class="text-center text-muted">No deductions recorded yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($deductions as $ded): ?>
                            <?php
                                $badgeClass = match($ded['status']) {
                                    'applied'   => 'bg-success',
                                    'cancelled' => 'bg-secondary',
                                    default     => 'bg-warning text-dark',
                                };
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo payrollText($ded['employee_fullname']); ?></strong>
                                    <?php if ($ded['employee_position']): ?>
                                        <br><small class="text-muted"><?php echo payrollText($ded['employee_position']); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><span class="badge bg-secondary"><?php echo payrollText($ded['deduction_type']); ?></span></td>
                                <td><?php echo payrollText($ded['description']); ?></td>
                                <td><?php echo $ded['incident_date'] ? payrollText($ded['incident_date']) : '—'; ?></td>
                                <td><strong><?php echo payrollMoney($ded['amount']); ?></strong></td>
                                <td><?php echo $ded['run_number'] ? payrollText($ded['run_number']) : '<span class="text-muted">—</span>'; ?></td>
                                <td><span class="badge <?php echo $badgeClass; ?>"><?php echo ucfirst($ded['status']); ?></span></td>
                                <td class="no-print">
                                    <?php if ($ded['status'] === 'pending'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="apply">
                                            <input type="hidden" name="ded_id" value="<?php echo (int)$ded['ded_id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-success" title="Mark as applied to payroll">
                                                <i class="fas fa-check"></i> Apply
                                            </button>
                                        </form>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Cancel this deduction?')">
                                            <input type="hidden" name="action" value="cancel">
                                            <input type="hidden" name="ded_id" value="<?php echo (int)$ded['ded_id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-secondary"><i class="fas fa-ban"></i></button>
                                        </form>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this deduction?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="ded_id" value="<?php echo (int)$ded['ded_id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

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

<!-- Add Deduction Modal -->
<div class="modal fade" id="addDeductionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Record Deduction</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label">Employee</label>
                            <select name="employee_id" class="form-select" required>
                                <option value="">Select employee</option>
                                <?php foreach ($employees as $emp): ?>
                                    <option value="<?php echo (int)$emp['employee_id']; ?>">
                                        <?php echo htmlspecialchars($emp['employee_fullname'] . ($emp['employee_position'] ? ' — ' . $emp['employee_position'] : '')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Deduction Type</label>
                            <select name="deduction_type" class="form-select" required>
                                <option value="Damages">Damages</option>
                                <option value="Missing">Missing</option>
                                <option value="Penalty">Penalty</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Incident Date</label>
                            <input type="date" name="incident_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Description</label>
                            <input type="text" name="description" class="form-control" placeholder="e.g. Damaged company vehicle side mirror" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount (MWK)</label>
                            <input type="number" step="0.01" min="0.01" name="amount" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Apply to Pay Run (optional)</label>
                            <select name="payroll_run_id" class="form-select">
                                <option value="">Not linked</option>
                                <?php foreach ($payRuns as $run): ?>
                                    <option value="<?php echo (int)$run['payroll_run_id']; ?>">
                                        <?php echo htmlspecialchars($run['run_number'] . ' (' . $run['pay_period_start'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </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"></i> Save Deduction</button>
                </div>
            </form>
        </div>
    </div>
</div>

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