<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

require_login();
$pageTitle = 'Payroll Management';

// Permission check
$can_manage = has_role(['admin', 'super_admin', 'accountant', 'finance_manager']);
$can_view = has_role(['admin', 'super_admin', 'accountant', 'finance_manager', 'hr_manager']);

if (!$can_view) {
    header('Location: index.php');
    exit;
}

$mysqli = db();
$currentMonth = date('n');
$currentYear = date('Y');

// Get company settings for payslip header
$companySettings = $mysqli->query("SELECT company_name, address_line, logo_url FROM shop_settings LIMIT 1")->fetch_assoc();
$companyName = $companySettings['company_name'] ?? 'SENARATH ENTERPRISES';
$companyAddress = $companySettings['address_line'] ?? '';
$logoUrl = $companySettings['logo_url'] ?? '';

// Get employees
$employees = $mysqli->query("SELECT e.id, e.full_name, e.emp_code, e.designation, e.base_salary, b.name as branch_name 
    FROM employees e 
    LEFT JOIN branches b ON b.id = e.branch_id 
    WHERE e.is_active = 1 ORDER BY e.emp_code");

//?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-cash-stack"></i> Payroll Management</h2>
        <div class="btn-group flex-wrap">
            <button class="btn btn-outline-primary active" onclick="showTab('process')">
                <i class="bi bi-calculator"></i> Process
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('salary-structure')">
                <i class="bi bi-sliders"></i> Salary
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('advances')">
                <i class="bi bi-cash-coin"></i> Advances
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('loans')">
                <i class="bi bi-bank"></i> Loans
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('deductions')">
                <i class="bi bi-dash-circle"></i> Deductions
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('settings')">
                <i class="bi bi-gear"></i> Settings
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('reports')">
                <i class="bi bi-graph-up"></i> Reports
            </button>
            <button class="btn btn-outline-primary" onclick="showTab('history')">
                <i class="bi bi-clock-history"></i> Payslip History
            </button>
        </div>
    </div>

    <!-- Process Payroll Tab -->
    <div id="tab-process" class="payroll-tab">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-calculator"></i> Monthly Payroll Processing</h5>
                <div class="d-flex gap-2">
                    <select id="payrollMonth" class="form-select form-select-sm" style="width: 120px;">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?= $m ?>" <?= $m == $currentMonth ? 'selected' : '' ?>><?= date('F', mktime(0, 0, 0, $m, 1)) ?></option>
                        <?php endfor; ?>
                    </select>
                    <select id="payrollYear" class="form-select form-select-sm" style="width: 100px;">
                        <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                            <option value="<?= $y ?>" <?= $y == $currentYear ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                    <button class="btn btn-primary btn-sm" onclick="calculatePayroll()">
                        <i class="bi bi-calculator"></i> Calculate
                    </button>
                    <button class="btn btn-success btn-sm" onclick="exportToExcel()" id="exportBtn" disabled>
                        <i class="bi bi-file-earmark-excel"></i> Export Excel
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="payrollCalculationResult" class="table-responsive">
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-calculator fs-1"></i>
                        <p>Select month and year, then click Calculate</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Salary Structure Tab -->
    <div id="tab-salary-structure" class="payroll-tab" style="display:none;">
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-person"></i> Select Employee</h5>
                    </div>
                    <div class="card-body p-0">
                        <div class="list-group list-group-flush" id="employeeList" style="max-height: 500px; overflow-y: auto;">
                            <?php while ($emp = $employees->fetch_assoc()): ?>
                                <button class="list-group-item list-group-item-action" 
                                        onclick="loadSalaryStructure(<?= $emp['id'] ?>)">
                                    <div class="d-flex justify-content-between">
                                        <span><?= htmlspecialchars($emp['emp_code']) ?></span>
                                        <small class="text-muted"><?= htmlspecialchars($emp['branch_name'] ?? '-') ?></small>
                                    </div>
                                    <div class="small"><?= htmlspecialchars($emp['full_name']) ?></div>
                                </button>
                            <?php endwhile; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-sliders"></i> Salary Structure</h5>
                    </div>
                    <div class="card-body" id="salaryStructureForm">
                        <div class="text-center py-5 text-muted">
                            <i class="bi bi-arrow-left fs-1"></i>
                            <p>Select an employee from the list</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Advances Tab -->
    <div id="tab-advances" class="payroll-tab" style="display:none;">
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-cash-coin"></i> Salary Advances</h5>
                        <?php if ($can_manage): ?>
                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#requestAdvanceModal">
                            <i class="bi bi-plus"></i> Request Advance
                        </button>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm" id="advancesTable">
                                <thead>
                                    <tr>
                                        <th>Employee</th>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Reason</th>
                                        <th>Repayment</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-clock-history"></i> Day Pay History</h5>
                    </div>
                    <div class="card-body">
                        <div id="dayPayHistory">
                            <p class="text-muted">Select an employee to view day pay history</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Reports Tab -->
    <div id="tab-reports" class="payroll-tab" style="display:none;">
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-building"></i> EPF/ETF Summary</h5>
                    </div>
                    <div class="card-body">
                        <div id="epfEtfSummary">
                            <p class="text-muted">Process payroll to view EPF/ETF summary</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-cash"></i> Bank Transfer List</h5>
                    </div>
                    <div class="card-body">
                        <div id="bankTransferList">
                            <p class="text-muted">Process payroll to view bank transfer list</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Payslip History Tab -->
    <div id="tab-history" class="payroll-tab" style="display:none;">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-clock-history"></i> Payslip History</h5>
                <div class="d-flex gap-2">
                    <select id="historyMonth" class="form-select form-select-sm" style="width: 120px;">
                        <option value="">All Months</option>
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?= $m ?>"><?= date('F', mktime(0, 0, 0, $m, 1)) ?></option>
                        <?php endfor; ?>
                    </select>
                    <select id="historyYear" class="form-select form-select-sm" style="width: 100px;">
                        <option value="">All Years</option>
                        <?php for ($y = date('Y') - 2; $y <= date('Y'); $y++): ?>
                            <option value="<?= $y ?>" <?= $y == $currentYear ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                    <button class="btn btn-primary btn-sm" onclick="loadPayslipHistory()">
                        <i class="bi bi-search"></i> Search
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="payslipHistoryResult" class="table-responsive">
                    <div class="text-center py-5 text-muted">
                        <i class="bi bi-clock-history fs-1"></i>
                        <p>Select month/year and click Search to view payslip history</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Loans Tab -->
    <div id="tab-loans" class="payroll-tab" style="display:none;">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5><i class="bi bi-bank"></i> Staff Loans</h5>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addLoanModal">
                <i class="bi bi-plus"></i> Add Loan
            </button>
        </div>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm" id="loansTable">
                        <thead class="table-dark">
                            <tr>
                                <th>Employee</th>
                                <th>Date</th>
                                <th>Principal</th>
                                <th>Interest%</th>
                                <th>Total</th>
                                <th>Monthly</th>
                                <th>Remaining</th>
                                <th>Status</th>
                                <th>Purpose</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td colspan="10" class="text-center">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Deductions Tab -->
    <div id="tab-deductions" class="payroll-tab" style="display:none;">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5><i class="bi bi-dash-circle"></i> Recurring Deductions</h5>
            <div class="d-flex gap-2">
                <input type="month" id="deductionFilterMonth" class="form-control" value="<?= date('Y-m') ?>" style="width: 150px;">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDeductionModal" onclick="loadDeductionTypes()">
                    <i class="bi bi-plus"></i> Add Deduction
                </button>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <div class="alert alert-info mb-2">
                        <i class="bi bi-info-circle"></i> Showing deductions applicable for <strong id="deductionMonthLabel"><?= date('F Y') ?></strong>
                    </div>
                    <table class="table table-sm" id="deductionsTable">
                        <thead class="table-dark">
                            <tr>
                                <th>Employee</th>
                                <th>Type</th>
                                <th>Amount (LKR)</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Reference</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td colspan="7" class="text-center">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Tab -->
    <div id="tab-settings" class="payroll-tab" style="display:none;">
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-3">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="bi bi-clock"></i> Overtime Settings</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Hours Threshold (per day)</label>
                            <input type="number" class="form-control" id="otHoursThreshold" value="8" step="0.5">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Normal Rate Multiplier</label>
                            <input type="number" class="form-control" id="otNormalRate" value="1.00" step="0.01">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">OT Rate Multiplier (> threshold)</label>
                            <input type="number" class="form-control" id="otRate" value="1.50" step="0.01">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Holiday/Weekend Rate</label>
                            <input type="number" class="form-control" id="otHolidayRate" value="2.00" step="0.01">
                        </div>
                        <button class="btn btn-primary" onclick="saveOvertimeSettings()">
                            <i class="bi bi-save"></i> Save OT Settings
                        </button>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="bi bi-calculator"></i> Tax Slabs (PAYE)</h5>
                        <button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#addTaxSlabModal">
                            <i class="bi bi-plus"></i> Add
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <select class="form-select form-select-sm" id="taxYearSelect" onchange="loadTaxSlabs()">
                                <option value="2024" selected>2024</option>
                                <option value="2025">2025</option>
                            </select>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-sm" id="taxSlabsTable">
                                <thead class="table-dark">
                                    <tr>
                                        <th>Slab</th>
                                        <th>Min Income</th>
                                        <th>Max Income</th>
                                        <th>Rate</th>
                                        <th>Fixed</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Request Advance Modal -->
<div class="modal fade" id="requestAdvanceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Request Salary Advance</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="advanceRequestForm" onsubmit="submitAdvanceRequest(event)">
                <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-select" required>
                            <option value="">Select Employee</option>
                            <?php 
                            $employees->data_seek(0);
                            while ($emp = $employees->fetch_assoc()): 
                            ?>
                                <option value="<?= $emp['id'] ?>"><?= htmlspecialchars($emp['emp_code'] . ' - ' . $emp['full_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount (LKR)</label>
                        <input type="number" name="amount" class="form-control" min="1" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reason</label>
                        <textarea name="reason" class="form-control" rows="2" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Repayment Method</label>
                        <select name="repayment_method" class="form-select" onchange="toggleInstallments(this)">
                            <option value="lump_sum">Lump Sum (next payroll)</option>
                            <option value="installments">Installments</option>
                        </select>
                    </div>
                    <div class="mb-3" id="installmentsDiv" style="display:none;">
                        <label class="form-label">Number of Installments</label>
                        <input type="number" name="total_installments" class="form-control" min="2" max="12" value="2">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Submit Request</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Payslip Modal -->
<div class="modal fade" id="payslipModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content" id="payslipContent">
            <!-- Payslip content loaded dynamically -->
        </div>
    </div>
</div>

<!-- Add Loan Modal -->
<div class="modal fade" id="addLoanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-bank"></i> Add Staff Loan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form onsubmit="submitLoan(event)">
                <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-select" required>
                            <option value="">Select Employee</option>
                            <?php $emps = $mysqli->query("SELECT id, emp_code, full_name FROM employees WHERE is_active = 1 ORDER BY full_name");
                            while ($e = $emps->fetch_assoc()): ?>
                                <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['emp_code'] . ' - ' . $e['full_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Loan Amount (LKR)</label>
                        <input type="number" name="loan_amount" class="form-control" step="0.01" min="1" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Interest Rate (%)</label>
                            <input type="number" name="interest_rate" class="form-control" step="0.01" min="0" value="0" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Total Installments</label>
                            <input type="number" name="total_installments" class="form-control" min="1" value="12" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Purpose</label>
                        <textarea name="purpose" class="form-control" rows="2" placeholder="Reason for loan..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Loan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Deduction Modal -->
<div class="modal fade" id="addDeductionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-dash-circle"></i> Add Recurring Deduction</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form onsubmit="submitDeduction(event)">
                <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-select" required>
                            <option value="">Select Employee</option>
                            <?php $emps = $mysqli->query("SELECT id, emp_code, full_name FROM employees WHERE is_active = 1 ORDER BY full_name");
                            while ($e = $emps->fetch_assoc()): ?>
                                <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['emp_code'] . ' - ' . $e['full_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Deduction Type</label>
                        <select name="deduction_type_id" class="form-select" id="deductionTypeSelect" required>
                            <option value="">Loading...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount (LKR per month)</label>
                        <input type="number" name="amount" class="form-control" step="0.01" min="0" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Start Date *</label>
                            <input type="date" name="start_date" id="deductionStartDate" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">End Date (optional)</label>
                            <input type="date" name="end_date" id="deductionEndDate" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reference Number</label>
                        <input type="text" name="reference_no" class="form-control" placeholder="e.g. Insurance Policy #123">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Remarks</label>
                        <textarea name="remarks" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Deduction</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Deduction Modal -->
<div class="modal fade" id="editDeductionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title"><i class="bi bi-pencil"></i> Edit Deduction</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form onsubmit="submitEditDeduction(event)">
                <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="id" id="editDeductionId">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" id="editDeductionEmployee" class="form-select" required>
                            <option value="">Select Employee</option>
                            <?php 
                            $empList = $mysqli->query("SELECT id, emp_code, full_name FROM employees WHERE is_active=1 ORDER BY full_name");
                            while ($e = $empList->fetch_assoc()): 
                            ?>
                                <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['emp_code'] . ' - ' . $e['full_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Deduction Type</label>
                        <select name="deduction_type_id" class="form-select" id="editDeductionType" required>
                            <option value="">Loading...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Monthly Amount (LKR)</label>
                        <input type="number" name="amount" id="editDeductionAmount" class="form-control" step="0.01" min="0" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" name="start_date" id="editDeductionStart" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">End Date (optional)</label>
                            <input type="date" name="end_date" id="editDeductionEnd" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reference Number</label>
                        <input type="text" name="reference_no" id="editDeductionRef" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Remarks</label>
                        <textarea name="remarks" id="editDeductionRemarks" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="is_active" id="editDeductionActive" class="form-check-input" value="1" checked>
                            <label class="form-check-label">Active</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Deduction</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Tax Slab Modal -->
<div class="modal fade" id="addTaxSlabModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="bi bi-calculator"></i> Add Tax Slab</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Slab Name</label>
                    <input type="text" id="taxSlabName" class="form-control" placeholder="e.g. 20% Tax Bracket">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Min Income (LKR)</label>
                        <input type="number" id="taxMinIncome" class="form-control" step="1" min="0">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Max Income (LKR)</label>
                        <input type="number" id="taxMaxIncome" class="form-control" step="1" min="0" placeholder="Leave blank for above">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Tax Rate (%)</label>
                        <input type="number" id="taxRate" class="form-control" step="0.01" min="0" max="100">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Fixed Amount (LKR)</label>
                        <input type="number" id="taxFixedAmount" class="form-control" step="0.01" min="0" value="0">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Effective Year</label>
                    <select id="taxSlabYear" class="form-select">
                        <option value="2024" selected>2024</option>
                        <option value="2025">2025</option>
                        <option value="2026">2026</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="saveTaxSlab()">
                    <i class="bi bi-save"></i> Save Tax Slab
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const canManage = <?= $can_manage ? 'true' : 'false' ?>;

function showTab(tabName) {
    document.querySelectorAll('.payroll-tab').forEach(tab => tab.style.display = 'none');
    document.getElementById('tab-' + tabName).style.display = 'block';
    
    document.querySelectorAll('.btn-group .btn').forEach(btn => btn.classList.remove('active'));
    
    // Handle both click events and programmatic calls
    if (typeof event !== 'undefined' && event && event.target) {
        event.target.classList.add('active');
    } else {
        // When called from URL, highlight the correct button
        document.querySelectorAll('.btn-group .btn').forEach(btn => {
            if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes("'" + tabName + "'")) {
                btn.classList.add('active');
            }
        });
    }
    
    if (tabName === 'advances') loadAdvances();
    if (tabName === 'loans') loadLoans();
    if (tabName === 'deductions') loadDeductions();
}

function calculatePayroll() {
    const month = $('#payrollMonth').val();
    const year = $('#payrollYear').val();
    
    $.get('api/payroll.php', {
        action: 'calculate_payroll',
        month: month,
        year: year
    }, function(res) {
        displayPayrollCalculation(res.data, month, year);
    });
}

function displayPayrollCalculation(data, month, year) {
    let html = `
        <table class="table table-sm table-hover">
            <thead class="table-dark">
                <tr>
                    <th>Emp Code</th>
                    <th>Name</th>
                    <th>Days Worked</th>
                    <th>Basic (LKR)</th>
                    <th>Allowance (LKR)</th>
                    <th>Gross (LKR)</th>
                    <th>EPF 8% (LKR)</th>
                    <th>Advance (LKR)</th>
                    <th>Deductions (LKR)</th>
                    <th>Net (LKR)</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    let totalBasic = 0, totalAllowance = 0, totalGross = 0, totalEPF = 0, totalAdvance = 0, totalRecurring = 0, totalNet = 0;
    
    data.forEach(emp => {
        totalBasic += emp.basic_salary;
        totalAllowance += (emp.allowance || 0);
        totalGross += emp.gross_salary;
        totalEPF += emp.epf_employee;
        totalAdvance += emp.advance_deduction;
        totalRecurring += (emp.recurring_deductions || 0);
        totalNet += emp.net_salary;
        
        html += `
            <tr data-employee='${JSON.stringify(emp)}'>
                <td>${emp.emp_code}</td>
                <td>${emp.full_name}</td>
                <td>${emp.days_worked || emp.attendance.present_days || 0}</td>
                <td class="text-end">${fmt(emp.basic_salary)}</td>
                <td class="text-end text-success">${fmt(emp.allowance || 0)}</td>
                <td class="text-end">${fmt(emp.gross_salary)}</td>
                <td class="text-end text-danger">${fmt(emp.epf_employee)}</td>
                <td class="text-end text-danger">${fmt(emp.advance_deduction)}</td>
                <td class="text-end text-danger" title="${emp.recurring_list?.map(d => d.name + ': ' + fmt(d.amount)).join(', ') || ''}">${fmt(emp.recurring_deductions || 0)}</td>
                <td class="text-end fw-bold">${fmt(emp.net_salary)}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick='previewPayslip(${JSON.stringify(emp)}, ${month}, ${year})'>
                        <i class="bi bi-eye"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
            <tfoot class="table-group-divider fw-bold">
                <tr class="table-primary">
                    <td colspan="3">TOTAL</td>
                    <td class="text-end">${fmt(totalBasic)}</td>
                    <td class="text-end">${fmt(totalAllowance)}</td>
                    <td class="text-end">${fmt(totalGross)}</td>
                    <td class="text-end">${fmt(totalEPF)}</td>
                    <td class="text-end">${fmt(totalAdvance)}</td>
                    <td class="text-end">${fmt(totalRecurring)}</td>
                    <td class="text-end">${fmt(totalNet)}</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    `;
    
    if (canManage) {
        html += `
            <div class="d-flex justify-content-end gap-2 mt-3">
                <button class="btn btn-success" onclick="processPayroll(${month}, ${year})">
                    <i class="bi bi-check-circle"></i> Process & Save Payroll
                </button>
                <button class="btn btn-outline-primary" onclick="printPayrollSummary()">
                    <i class="bi bi-printer"></i> Print Summary
                </button>
            </div>
        `;
    }
    
    $('#payrollCalculationResult').html(html);
    $('#exportBtn').prop('disabled', false);
}

function processPayroll(month, year) {
    const employees = [];
    $('#payrollCalculationResult tbody tr').each(function() {
        employees.push($(this).data('employee'));
    });
    
    $.post('api/payroll.php', {
        action: 'process_payroll',
        csrf: '<?= $_SESSION['csrf_token'] ?>',
        month: month,
        year: year,
        payroll_data: JSON.stringify(employees)
    }, function(res) {
        alert(res.message);
        if (res.message.includes('success')) {
            loadPayrollList(month, year);
        }
    });
}

function previewPayslip(emp, month, year) {
    const monthName = new Date(year, month - 1).toLocaleString('default', { month: 'long' });
    const first = `${year}-${String(month).padStart(2, '0')}-01`;
    const last = new Date(year, month, 0).toISOString().split('T')[0];
    
    let html = `
        <div class="modal-header">
            <h5 class="modal-title">Payslip - ${emp.full_name}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
            <style>
                .payslip-body { background:#fff; font-size:13px; line-height:1.2; }
                .slip { max-width:210mm; margin:0 auto; border:1px solid #dee2e6; padding:10mm; }
                .header { border-bottom:1px solid #dee2e6; padding-bottom:8px; margin-bottom:10px; }
                .company { font-weight:600; font-size:15px; }
                .meta label { width:130px; display:inline-block; color:#6c757d; margin-bottom:2px; }
                .table-sm th, .table-sm td { padding:0.2rem 0.5rem; font-size:12px; }
                h6 { font-size:13px; margin-bottom:5px; }
                .company-logo { max-height:60px; max-width:200px; }
                @media print {
                    @page { size: A4; margin: 10mm; }
                    body > * { display: none !important; }
                    .modal { display: block !important; position: absolute; left: 0; top: 0; width: 100%; height: auto; }
                    .modal-dialog { display: block !important; max-width: 100%; margin: 0; }
                    .modal-content { display: block !important; border: none; box-shadow: none; }
                    .modal-header, .modal-footer, .no-print { display: none !important; }
                    .modal-body { display: block !important; padding: 0; }
                    .slip { border: none; padding: 0; max-width: 100%; margin: 0; }
                }
            </style>
            <div class="payslip-body">
                <div class="slip">
                    <div class="d-flex justify-content-between align-items-start header">
                        <div>
                            <?php if (!empty($logoUrl)): ?>
                            <div class="mb-1"><img src="<?= htmlspecialchars($logoUrl) ?>" alt="Company Logo" class="company-logo"></div>
                            <?php endif; ?>
                            <div class="company"><?= htmlspecialchars($companyName) ?></div>
                            <div><?= htmlspecialchars($companyAddress) ?></div>
                        </div>
                        <div class="text-end">
                            <button class="btn btn-primary btn-sm no-print" onclick="printPayslip()">Print</button>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-7 meta">
                            <div><label>Employee:</label> <strong>${emp.full_name}</strong> (${emp.emp_code})</div>
                            <div><label>Period:</label> ${monthName} ${year}</div>
                            <div><label>Generated On:</label> ${new Date().toISOString().split('T')[0]}</div>
                        </div>
                        <div class="col-md-5">
                            <table class="table table-sm">
                                <tbody>
                                    <tr><th>Gross Salary</th><td class="text-end">${fmt(emp.gross_salary)}</td></tr>
                                    <tr><th>Total Allowances</th><td class="text-end">${fmt(emp.allowance || 0)}</td></tr>
                                    <tr><th>Total OT</th><td class="text-end">${fmt(emp.overtime_amount || 0)}</td></tr>
                                    <tr><th>Total Advances</th><td class="text-end">${fmt(emp.advance_deduction)}</td></tr>
                                    <tr><th>Total Deductions</th><td class="text-end">${fmt((emp.recurring_deductions || 0) + emp.loan_deduction + emp.nopay_deduction)}</td></tr>
                                    <tr class="table-light"><th>Net Salary</th><td class="text-end"><strong>${fmt(emp.net_salary)}</strong></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    ${emp.allowance > 0 ? `
                    <div class="mb-3">
                        <h6>Allowance (${first} to ${last})</h6>
                        <table class="table table-sm align-middle">
                            <thead><tr><th style="width:120px;">Type</th><th>Amount</th></tr></thead>
                            <tbody>
                                <tr><td>Excess Allowance</td><td class="text-end">${fmt(emp.allowance)}</td></tr>
                                <tr class="table-light"><th class="text-end">Total</th><th class="text-end">${fmt(emp.allowance)}</th></tr>
                            </tbody>
                        </table>
                    </div>
                    ` : ''}

                    ${emp.advance_deduction > 0 && emp.advances && emp.advances.length > 0 ? `
                    <div class="mb-3">
                        <h6>Advances (${first} to ${last})</h6>
                        <table class="table table-sm align-middle">
                            <thead><tr><th style="width:120px;">Date</th><th>Reason</th><th class="text-end" style="width:160px;">Amount</th></tr></thead>
                            <tbody>
                                ${emp.advances.map(adv => `
                                <tr>
                                    <td>${new Date(adv.advance_date).toLocaleDateString()}</td>
                                    <td>${adv.reason || 'Salary Advance'}</td>
                                    <td class="text-end">${fmt(adv.amount)}</td>
                                </tr>
                                `).join('')}
                                <tr class="table-light">
                                    <th colspan="2" class="text-end">Total</th>
                                    <th class="text-end">${fmt(emp.advance_deduction)}</th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    ` : ''}

                    <div class="mb-3">
                        <h6>Attendance Summary (${monthName} ${year})</h6>
                        <table class="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th>Working Days</th>
                                    <th>Present</th>
                                    <th>Leave</th>
                                    <th>Half Day</th>
                                    <th>OT Hours</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>${emp.attendance?.total_days || emp.days_worked || 0} days</td>
                                    <td>${emp.attendance?.present_days || 0} days</td>
                                    <td>${emp.attendance?.absent_days || 0} days</td>
                                    <td>${emp.attendance?.half_days || 0} days</td>
                                    <td>${emp.attendance?.overtime_hours || 0} hrs</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="row mt-4">
                        <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Employee Signature</div>
                        <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Authorized Signature</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
    `;
    
    $('#payslipContent').html(html);
    new bootstrap.Modal(document.getElementById('payslipModal')).show();
}

function loadSalaryStructure(employeeId) {
    $('#employeeList .active').removeClass('active');
    event.target.closest('.list-group-item').classList.add('active');
    
    $.get('api/payroll.php', {
        action: 'get_salary_structure',
        employee_id: employeeId
    }, function(res) {
        const data = res.data;
        let html = `
            <form id="salaryStructureFormData" onsubmit="saveSalaryStructure(event, ${employeeId})">
                <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="employee_id" value="${employeeId}">
                
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary mb-3">Basic Salary & Allowances</h6>
                        <div class="mb-3">
                            <label class="form-label">Basic Salary (LKR)</label>
                            <input type="number" name="basic_salary" class="form-control" 
                                value="${data.basic_salary || 0}" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Transport Allowance (LKR)</label>
                            <input type="number" name="transport_allowance" class="form-control" 
                                value="${data.transport_allowance || 0}" step="0.01">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Meal Allowance (LKR)</label>
                            <input type="number" name="meal_allowance" class="form-control" 
                                value="${data.meal_allowance || 0}" step="0.01">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Other Allowance (LKR)</label>
                            <input type="number" name="other_allowance" class="form-control" 
                                value="${data.other_allowance || 0}" step="0.01">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <h6 class="text-primary mb-3">Day Pay Settings</h6>
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="is_daily_wage" 
                                    id="isDailyWage" ${data.is_daily_wage ? 'checked' : ''} 
                                    onchange="toggleDayPay(this)">
                                <label class="form-check-label" for="isDailyWage">
                                    Daily Wage Employee
                                </label>
                            </div>
                        </div>
                        <div class="mb-3" id="dayPayRateDiv" style="${data.is_daily_wage ? '' : 'display:none;'}">
                            <label class="form-label">Day Pay Rate (LKR)</label>
                            <input type="number" name="day_pay_rate" class="form-control" 
                                value="${data.day_pay_rate || 0}" step="0.01">
                            <div class="form-text">Payment per day worked</div>
                        </div>
                        
                        <h6 class="text-primary mb-3 mt-4">Effective Date</h6>
                        <div class="mb-3">
                            <input type="date" name="effective_date" class="form-control" 
                                value="${data.effective_date || new Date().toISOString().split('T')[0]}">
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-end gap-2">
                    <button type="button" class="btn btn-secondary" onclick="loadDayPayHistory(${employeeId})">
                        <i class="bi bi-clock-history"></i> View Day Pay History
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Save Structure
                    </button>
                </div>
            </form>
            
            <div id="dayPayHistorySection" class="mt-4" style="display:none;">
                <h6 class="text-primary">Day Pay Change History</h6>
                <div id="dayPayHistoryContent"></div>
            </div>
        `;
        $('#salaryStructureForm').html(html);
        
        // Also load day pay history
        loadDayPayHistory(employeeId);
    });
}

function toggleDayPay(checkbox) {
    $('#dayPayRateDiv').toggle(checkbox.checked);
}

function saveSalaryStructure(e, employeeId) {
    e.preventDefault();
    $.post('api/payroll.php?action=save_salary_structure', $(e.target).serialize(), function(res) {
        alert(res.message);
    });
}

function loadDayPayHistory(employeeId) {
    $.get('api/payroll.php', {
        action: 'get_day_pay_history',
        employee_id: employeeId
    }, function(res) {
        let html = '<table class="table table-sm"><thead><tr><th>Date</th><th>Old Rate</th><th>New Rate</th><th>Reason</th></tr></thead><tbody>';
        res.data.forEach(h => {
            html += `<tr>
                <td>${h.effective_date}</td>
                <td>${fmt(h.old_rate)}</td>
                <td>${fmt(h.new_rate)}</td>
                <td>${h.change_reason || '-'}</td>
            </tr>`;
        });
        html += '</tbody></table>';
        $('#dayPayHistoryContent').html(html);
        $('#dayPayHistorySection').show();
    });
}

function loadAdvances() {
    $.get('api/payroll.php', { action: 'list_advances' }, function(res) {
        let html = '';
        res.data.forEach(adv => {
            const statusBadge = {
                'pending': '<span class="badge bg-warning">Pending</span>',
                'approved': '<span class="badge bg-success">Approved</span>',
                'rejected': '<span class="badge bg-danger">Rejected</span>',
                'repaid': '<span class="badge bg-secondary">Repaid</span>'
            }[adv.status];
            
            html += `<tr>
                <td>${adv.emp_code}<br><small>${adv.full_name}</small></td>
                <td>${adv.advance_date}</td>
                <td>${fmt(adv.amount)}</td>
                <td>${adv.reason}</td>
                <td>${adv.repayment_method === 'installments' ? adv.total_installments + ' months' : 'Lump sum'}</td>
                <td>${statusBadge}</td>
                <td>
                    ${canManage && adv.status === 'pending' ? `
                        <button class="btn btn-sm btn-success" onclick="approveAdvance(${adv.id}, 'approved')">Approve</button>
                        <button class="btn btn-sm btn-danger" onclick="approveAdvance(${adv.id}, 'rejected')">Reject</button>
                    ` : '-'}
                </td>
            </tr>`;
        });
        $('#advancesTable tbody').html(html);
    });
}

function submitAdvanceRequest(e) {
    e.preventDefault();
    $.post('api/payroll.php?action=request_advance', $(e.target).serialize(), function(res) {
        alert(res.message);
        if (res.message.includes('submitted')) {
            $('#requestAdvanceModal').modal('hide');
            loadAdvances();
        }
    });
}

function approveAdvance(id, status) {
    $.post('api/payroll.php', {
        action: 'approve_advance',
        csrf: '<?= $_SESSION['csrf_token'] ?>',
        id: id,
        status: status
    }, function(res) {
        alert(res.message);
        loadAdvances();
    });
}

function toggleInstallments(select) {
    $('#installmentsDiv').toggle(select.value === 'installments');
}

function fmt(n) {
    return Number(n || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

function printPayslip() {
    const content = document.querySelector('.payslip-container').innerHTML;
    const win = window.open('', '_blank');
    win.document.write(`
        <html><head><title>Payslip</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>body { padding: 20px; }</style>
        </head><body>${content}</body></html>
    `);
    win.document.close();
    win.print();
}

function printPayrollSummary() {
    window.print();
}

// URL parameter handling for tab switching
const urlParams = new URLSearchParams(window.location.search);
const tabParam = urlParams.get('tab');

if (tabParam) {
    $(function() {
        showTab(tabParam);
        if (tabParam === 'loans') loadLoans();
        if (tabParam === 'deductions') loadDeductions();
        if (tabParam === 'settings') loadSettings();
    });
} else {
    $(function() {
        calculatePayroll();
    });
}

// === LOANS MANAGEMENT ===
function loadLoans() {
    $.get('api/payroll.php', { action: 'list_loans' }, function(res) {
        let html = '';
        const csrf = document.querySelector('input[name="csrf"]').value;
        res.data.forEach(loan => {
            const statusBadge = loan.status === 'active' 
                ? '<span class="badge bg-success">Active</span>'
                : '<span class="badge bg-secondary">Completed</span>';
            
            // Add close button only for active loans
            const closeBtn = loan.status === 'active' 
                ? `<button class="btn btn-sm btn-warning" onclick="closeLoan(${loan.id}, '${csrf}')">Close</button>`
                : '-';
            
            html += `<tr>
                <td>${loan.emp_code}<br><small>${loan.full_name}</small></td>
                <td>${loan.loan_date}</td>
                <td>${fmt(loan.loan_amount)}</td>
                <td>${loan.interest_rate}%</td>
                <td>${fmt(loan.total_payable)}</td>
                <td>${fmt(loan.monthly_installment)}</td>
                <td>${fmt(loan.remaining_amount)}</td>
                <td>${statusBadge}</td>
                <td>${loan.purpose || '-'}</td>
                <td>${closeBtn}</td>
            </tr>`;
        });
        $('#loansTable tbody').html(html || '<tr><td colspan="10" class="text-center">No active loans</td></tr>');
    });
}

function closeLoan(loanId, csrf) {
    if (!confirm('Are you sure you want to close this loan? Remaining balance will be cleared.')) return;
    
    $.post('api/payroll.php?action=close_loan', { loan_id: loanId, csrf: csrf }, function(res) {
        alert(res.message);
        if (res.message.includes('success')) {
            loadLoans();
        }
    }).fail(function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to close loan'));
    });
}

function submitLoan(e) {
    e.preventDefault();
    const form = $(e.target);
    const total = parseFloat(form.find('[name="loan_amount"]').val());
    const interest = parseFloat(form.find('[name="interest_rate"]').val());
    const installments = parseInt(form.find('[name="total_installments"]').val());
    const totalPayable = total * (1 + interest/100);
    const monthly = totalPayable / installments;
    
    if (!confirm(`Loan Summary:\nPrincipal: ${fmt(total)}\nInterest: ${interest}%\nTotal Payable: ${fmt(totalPayable)}\nMonthly: ${fmt(monthly)} for ${installments} months\n\nProceed?`)) return;
    
    $.post('api/payroll.php?action=create_loan', form.serialize(), function(res) {
        alert(res.message);
        if (res.message.includes('success')) {
            $('#addLoanModal').modal('hide');
            form[0].reset();
            loadLoans();
        }
    });
}

// === DEDUCTIONS MANAGEMENT ===
function loadDeductions() {
    const filterMonth = $('#deductionFilterMonth').val(); // Format: YYYY-MM
    const [year, month] = filterMonth.split('-');
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 
                        'July', 'August', 'September', 'October', 'November', 'December'];
    $('#deductionMonthLabel').text(monthNames[month-1] + ' ' + year);
    
    $.get('api/payroll.php', { action: 'list_deductions', month: filterMonth }, function(res) {
        let html = '';
        res.data.forEach(ded => {
            html += `<tr>
                <td>${ded.emp_code}<br><small>${ded.full_name}</small></td>
                <td>${ded.deduction_name}</td>
                <td class="text-end fw-bold">${fmt(ded.amount)}</td>
                <td>${ded.start_date}</td>
                <td>${ded.end_date || 'Ongoing'}</td>
                <td>${ded.reference_no || '-'}</td>
                <td>
                    <button class="btn btn-sm btn-warning" onclick="editDeduction(${ded.id})" title="Edit">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteDeduction(${ded.id})" title="Delete">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            </tr>`;
        });
        $('#deductionsTable tbody').html(html || '<tr><td colspan="7" class="text-center text-muted">No deductions for this month</td></tr>');
    });
}

// Watch for month filter change
$('#deductionFilterMonth').on('change', loadDeductions);

function loadDeductionTypes() {
    $.get('api/payroll.php', { action: 'list_deduction_types' }, function(res) {
        let options = '<option value="">Select Type</option>';
        res.data.forEach(dt => {
            options += `<option value="${dt.id}">${dt.name} (${dt.code})</option>`;
        });
        $('#deductionTypeSelect').html(options);
    });
}

function submitDeduction(e) {
    e.preventDefault();
    const form = e.target;
    
    // Ensure start_date has a value
    let startDate = $('#deductionStartDate').val();
    if (!startDate) {
        startDate = new Date().toISOString().split('T')[0]; // Today as default
        $('#deductionStartDate').val(startDate);
    }
    
    // Debug: Log form values
    console.log('Form data:', $(form).serialize());
    
    $.post('api/payroll.php?action=create_deduction', $(form).serialize(), function(res) {
        alert(res.message);
        if (res.message.includes('success')) {
            $('#addDeductionModal').modal('hide');
            form.reset();
            // Set default dates after reset
            $('#deductionStartDate').val(new Date().toISOString().split('T')[0]);
            loadDeductions();
        }
    }).fail(function(xhr) {
        console.error('Error response:', xhr.responseText);
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to save deduction'));
    });
}

function editDeduction(id) {
    // Load deduction types first
    loadDeductionTypesForEdit();
    
    $.get('api/payroll.php', { action: 'get_deduction', id: id }, function(res) {
        if (res.data) {
            const ded = res.data;
            $('#editDeductionId').val(ded.id);
            $('#editDeductionEmployee').val(ded.employee_id);
            $('#editDeductionType').val(ded.deduction_type_id);
            $('#editDeductionAmount').val(ded.amount);
            $('#editDeductionStart').val(ded.start_date);
            $('#editDeductionEnd').val(ded.end_date || '');
            $('#editDeductionRef').val(ded.reference_no || '');
            $('#editDeductionRemarks').val(ded.remarks || '');
            $('#editDeductionActive').prop('checked', ded.is_active == 1);
            
            $('#editDeductionModal').modal('show');
        }
    }).fail(function() {
        alert('Error: Could not load deduction data');
    });
}

function loadDeductionTypesForEdit() {
    $.get('api/payroll.php', { action: 'list_deduction_types' }, function(res) {
        let options = '<option value="">Select Type</option>';
        res.data.forEach(dt => {
            options += `<option value="${dt.id}">${dt.name} (${dt.code})</option>`;
        });
        $('#editDeductionType').html(options);
    });
}

function submitEditDeduction(e) {
    e.preventDefault();
    const formData = $(e.target).serialize();
    
    $.post('api/payroll.php?action=update_deduction', formData, function(res) {
        alert(res.message);
        if (res.message.includes('success') || res.message.includes('Updated')) {
            $('#editDeductionModal').modal('hide');
            e.target.reset();
            loadDeductions();
        }
    }).fail(function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to update deduction'));
    });
}

function deleteDeduction(id) {
    if (!confirm('Are you sure you want to delete this deduction?')) return;
    
    const csrf = $('input[name="csrf"]').first().val();
    
    $.post('api/payroll.php?action=delete_deduction', { id: id, csrf: csrf }, function(res) {
        alert(res.message);
        if (res.message.includes('success') || res.message.includes('deleted')) {
            loadDeductions();
        }
    }).fail(function(xhr) {
        alert('Error: ' + (xhr.responseJSON?.message || 'Failed to delete deduction'));
    });
}

// === SETTINGS ===
function loadSettings() {
    // Load OT Settings
    $.get('api/payroll.php', { action: 'get_overtime_settings' }, function(res) {
        if (res.data) {
            $('#otHoursThreshold').val(res.data.hours_threshold);
            $('#otNormalRate').val(res.data.normal_rate);
            $('#otRate').val(res.data.ot_rate);
            $('#otHolidayRate').val(res.data.holiday_rate);
        }
    });
    
    // Load Tax Slabs
    loadTaxSlabs();
}

function loadTaxSlabs() {
    const year = $('#taxYearSelect').val() || new Date().getFullYear();
    $.get('api/payroll.php', { action: 'get_tax_slabs', year: year }, function(res) {
        let html = '';
        res.data.forEach(slab => {
            html += `<tr>
                <td>${slab.slab_name}</td>
                <td>${fmt(slab.min_income)}</td>
                <td>${slab.max_income ? fmt(slab.max_income) : 'Above'}</td>
                <td>${slab.tax_rate}%</td>
                <td>${fmt(slab.fixed_amount)}</td>
            </tr>`;
        });
        $('#taxSlabsTable tbody').html(html || '<tr><td colspan="5" class="text-center">No tax slabs defined</td></tr>');
    });
}

function saveOvertimeSettings() {
    $.post('api/payroll.php', {
        action: 'save_overtime_settings',
        csrf: '<?= $_SESSION['csrf_token'] ?>',
        hours_threshold: $('#otHoursThreshold').val(),
        normal_rate: $('#otNormalRate').val(),
        ot_rate: $('#otRate').val(),
        holiday_rate: $('#otHolidayRate').val()
    }, function(res) {
        alert(res.message);
    });
}

function saveTaxSlab() {
    $.post('api/payroll.php', {
        action: 'save_tax_slab',
        csrf: '<?= $_SESSION['csrf_token'] ?>',
        slab_name: $('#taxSlabName').val(),
        min_income: $('#taxMinIncome').val(),
        max_income: $('#taxMaxIncome').val(),
        tax_rate: $('#taxRate').val(),
        fixed_amount: $('#taxFixedAmount').val(),
        effective_year: $('#taxSlabYear').val()
    }, function(res) {
        alert(res.message);
        if (res.message.includes('success') || res.message.includes('added')) {
            $('#addTaxSlabModal').modal('hide');
            document.getElementById('addTaxSlabForm').reset();
            loadTaxSlabs();
        }
    });
}

function printPayslip() {
    const payslipContent = document.querySelector('.payslip-body').innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Payslip</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
            <style>
                body { background:#fff; font-size:13px; line-height:1.2; }
                .slip { max-width:210mm; margin:0 auto; padding:10mm; }
                .header { border-bottom:1px solid #dee2e6; padding-bottom:8px; margin-bottom:10px; }
                .company { font-weight:600; font-size:15px; }
                .meta label { width:130px; display:inline-block; color:#6c757d; margin-bottom:2px; }
                .table-sm th, .table-sm td { padding:0.2rem 0.5rem; font-size:12px; }
                h6 { font-size:13px; margin-bottom:5px; }
                .company-logo { max-height:60px; max-width:200px; }
                .no-print { display: none !important; }
                @media print { @page { size: A4; margin: 10mm; } }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            <div class="slip">${payslipContent}</div>
        </body>
        </html>
    `);
    printWindow.document.close();
}

function exportToExcel() {
    const month = $('#payrollMonth').val();
    const year = $('#payrollYear').val();
    const monthName = new Date(year, month - 1).toLocaleString('default', { month: 'long' });
    
    // Get payroll data from table
    const rows = [];
    $('#payrollCalculationResult tbody tr').each(function() {
        const emp = $(this).data('employee');
        rows.push({
            'Employee Code': emp.emp_code,
            'Name': emp.full_name,
            'Days Worked': emp.days_worked || emp.attendance?.present_days || 0,
            'Basic Salary (LKR)': emp.basic_salary,
            'Allowance (LKR)': emp.allowance || 0,
            'Gross Salary (LKR)': emp.gross_salary,
            'EPF 8% (LKR)': emp.epf_employee,
            'Advance Deduction (LKR)': emp.advance_deduction,
            'Recurring Deductions (LKR)': emp.recurring_deductions || 0,
            'Net Salary (LKR)': emp.net_salary
        });
    });
    
    // Get totals from footer
    const totalRow = {
        'Employee Code': 'TOTAL',
        'Name': '',
        'Days Worked': '',
        'Basic Salary (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(4)').text(),
        'Allowance (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(5)').text(),
        'Gross Salary (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(6)').text(),
        'EPF 8% (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(7)').text(),
        'Advance Deduction (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(8)').text(),
        'Recurring Deductions (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(9)').text(),
        'Net Salary (LKR)': $('#payrollCalculationResult tfoot tr td:nth-child(10)').text()
    };
    rows.push(totalRow);
    
    // Create CSV content
    let csv = 'Employee Code,Name,Days Worked,Basic Salary (LKR),Allowance (LKR),Gross Salary (LKR),EPF 8% (LKR),Advance Deduction (LKR),Recurring Deductions (LKR),Net Salary (LKR)\n';
    
    rows.forEach(row => {
        const line = [
            row['Employee Code'],
            row['Name'],
            row['Days Worked'],
            row['Basic Salary (LKR)'],
            row['Allowance (LKR)'],
            row['Gross Salary (LKR)'],
            row['EPF 8% (LKR)'],
            row['Advance Deduction (LKR)'],
            row['Recurring Deductions (LKR)'],
            row['Net Salary (LKR)']
        ].join(',');
        csv += line + '\n';
    });
    
    // Create download link
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `Payroll_${monthName}_${year}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function loadPayslipHistory() {
    const month = $('#historyMonth').val();
    const year = $('#historyYear').val();
    
    $.get('api/payroll.php', {
        action: 'get_payroll_history',
        month: month,
        year: year
    }, function(res) {
        displayPayslipHistory(res.data);
    });
}

function displayPayslipHistory(data) {
    if (!data || data.length === 0) {
        $('#payslipHistoryResult').html('<div class="text-center py-5 text-muted"><i class="bi bi-inbox fs-1"></i><p>No payslip history found for the selected period.</p></div>');
        return;
    }
    
    let totalBasic = 0, totalGross = 0, totalEPF = 0, totalNet = 0;
    
    let html = `
        <table class="table table-sm table-hover">
            <thead class="table-dark">
                <tr>
                    <th>Employee</th>
                    <th>Month</th>
                    <th>Year</th>
                    <th>Days Worked</th>
                    <th>Basic (LKR)</th>
                    <th>Gross (LKR)</th>
                    <th>EPF (LKR)</th>
                    <th>Net (LKR)</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    data.forEach(record => {
        totalBasic += parseFloat(record.basic_salary);
        totalGross += parseFloat(record.gross_salary);
        totalEPF += parseFloat(record.epf_employee);
        totalNet += parseFloat(record.net_salary);
        
        const monthName = new Date(record.payroll_year, record.payroll_month - 1).toLocaleString('default', { month: 'long' });
        html += `
            <tr>
                <td>${record.employee_name || record.emp_code}</td>
                <td>${monthName}</td>
                <td>${record.payroll_year}</td>
                <td>${record.days_worked || record.present_days}</td>
                <td class="text-end">${fmt(record.basic_salary)}</td>
                <td class="text-end">${fmt(record.gross_salary)}</td>
                <td class="text-end">${fmt(record.epf_employee)}</td>
                <td class="text-end fw-bold">${fmt(record.net_salary)}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="viewHistoricalPayslip(${record.id})">
                        <i class="bi bi-eye"></i> View Payslip
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
            <tfoot class="table-group-divider fw-bold">
                <tr class="table-primary">
                    <td colspan="4">TOTAL</td>
                    <td class="text-end">${fmt(totalBasic)}</td>
                    <td class="text-end">${fmt(totalGross)}</td>
                    <td class="text-end">${fmt(totalEPF)}</td>
                    <td class="text-end">${fmt(totalNet)}</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    `;
    
    $('#payslipHistoryResult').html(html);
}

function viewHistoricalPayslip(payrollId) {
    $.get('api/payroll.php', {
        action: 'get_payslip_details',
        payroll_id: payrollId
    }, function(res) {
        const data = res.data;
        const monthName = new Date(data.payroll_year, data.payroll_month - 1).toLocaleString('default', { month: 'long' });
        previewHistoricalPayslip(data, monthName);
    });
}

function previewHistoricalPayslip(data, monthName) {
    const html = `
        <div class="modal-header">
            <h5 class="modal-title">Payslip - ${data.employee_name} (${monthName} ${data.payroll_year})</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
            <style>
                .payslip-body { background:#fff; font-size:13px; line-height:1.2; }
                .slip { max-width:210mm; margin:0 auto; border:1px solid #dee2e6; padding:10mm; }
                .header { border-bottom:1px solid #dee2e6; padding-bottom:8px; margin-bottom:10px; }
                .company { font-weight:600; font-size:15px; }
                .meta label { width:130px; display:inline-block; color:#6c757d; margin-bottom:2px; }
                .table-sm th, .table-sm td { padding:0.2rem 0.5rem; font-size:12px; }
                h6 { font-size:13px; margin-bottom:5px; }
                .company-logo { max-height:60px; max-width:200px; }
                @media print {
                    @page { size: A4; margin: 10mm; }
                    body > * { display: none !important; }
                    .modal { display: block !important; position: absolute; left: 0; top: 0; width: 100%; height: auto; }
                    .modal-dialog { display: block !important; max-width: 100%; margin: 0; }
                    .modal-content { display: block !important; border: none; box-shadow: none; }
                    .modal-header, .modal-footer, .no-print { display: none !important; }
                    .modal-body { display: block !important; padding: 0; }
                    .slip { border: none; padding: 0; max-width: 100%; margin: 0; }
                }
            </style>
            <div class="payslip-body">
                <div class="slip">
                    <div class="d-flex justify-content-between align-items-start header">
                        <div>
                            <?php if (!empty($logoUrl)): ?>
                            <div class="mb-1"><img src="<?= htmlspecialchars($logoUrl) ?>" alt="Company Logo" class="company-logo"></div>
                            <?php endif; ?>
                            <div class="company"><?= htmlspecialchars($companyName) ?></div>
                            <div><?= htmlspecialchars($companyAddress) ?></div>
                        </div>
                        <div class="text-end">
                            <button class="btn btn-primary btn-sm no-print" onclick="printHistoricalPayslip()">Print</button>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-7 meta">
                            <div><label>Employee:</label> <strong>${data.employee_name}</strong> (${data.emp_code})</div>
                            <div><label>Designation:</label> ${data.designation || ''}</div>
                            <div><label>Branch:</label> ${data.branch_name || ''}</div>
                            <div><label>Period:</label> ${monthName} ${data.payroll_year}</div>
                            <div><label>Generated On:</label> ${data.created_at ? data.created_at.split(' ')[0] : ''}</div>
                        </div>
                        <div class="col-md-5">
                            <table class="table table-sm">
                                <tbody>
                                    <tr><th>Gross Salary</th><td class="text-end">${fmt(data.gross_salary)}</td></tr>
                                    <tr><th>Total Allowances</th><td class="text-end">${fmt((data.transport_allowance || 0) + (data.meal_allowance || 0) + (data.other_allowance || 0))}</td></tr>
                                    <tr><th>Total Deductions</th><td class="text-end">${fmt((data.epf_employee || 0) + (data.advance_deduction || 0) + (data.other_deductions || 0))}</td></tr>
                                    <tr class="table-light"><th>Net Salary</th><td class="text-end"><strong>${fmt(data.net_salary)}</strong></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="mb-3">
                        <h6>Attendance Summary (${monthName} ${data.payroll_year})</h6>
                        <div class="table-responsive">
                            <table class="table table-sm align-middle">
                                <thead>
                                    <tr>
                                        <th>Working Days</th>
                                        <th>Present</th>
                                        <th>Leave</th>
                                        <th>Half Day</th>
                                        <th>OT Hours</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>${data.total_days || data.days_worked || 0} days</td>
                                        <td>${data.present_days || 0} days</td>
                                        <td>${data.absent_days || 0} days</td>
                                        <td>${data.half_days || 0} days</td>
                                        <td>${data.overtime_hours || 0} hrs</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="mb-3">
                        <h6>Employer Contributions</h6>
                        <table class="table table-sm">
                            <tbody>
                                <tr><th>EPF (12%)</th><td class="text-end">${fmt(data.epf_employer || 0)}</td></tr>
                                <tr><th>ETF (3%)</th><td class="text-end">${fmt(data.etf_employer || 0)}</td></tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="row mt-4">
                        <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Employee Signature</div>
                        <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Authorized Signature</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
    `;
    
    $('#payslipContent').html(html);
    new bootstrap.Modal(document.getElementById('payslipModal')).show();
}

function printHistoricalPayslip() {
    const payslipContent = document.querySelector('.payslip-body').innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Payslip</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
            <style>
                body { background:#fff; font-size:13px; line-height:1.2; }
                .slip { max-width:210mm; margin:0 auto; padding:10mm; }
                .header { border-bottom:1px solid #dee2e6; padding-bottom:8px; margin-bottom:10px; }
                .company { font-weight:600; font-size:15px; }
                .meta label { width:130px; display:inline-block; color:#6c757d; margin-bottom:2px; }
                .table-sm th, .table-sm td { padding:0.2rem 0.5rem; font-size:12px; }
                h6 { font-size:13px; margin-bottom:5px; }
                .company-logo { max-height:60px; max-width:200px; }
                .no-print { display: none !important; }
                @media print { @page { size: A4; margin: 10mm; } }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            <div class="slip">${payslipContent}</div>
        </body>
        </html>
    `);
    printWindow.document.close();
}
</script>

<style>
.payslip-container {
    background: white;
}
.table thead.table-dark th {
    background-color: #212529 !important;
    color: white !important;
    font-weight: 600;
}
@media print {
    .btn, .modal-header, .modal-footer { display: none !important; }
    .payslip-container { border: none !important; }
}
</style>

