<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/accounting.php';
requireLogin();

// ── AJAX quick-add ─────────────────────────────────────────
if (($_GET['ajax'] ?? '') === 'quick_add') {
    header('Content-Type: application/json');
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) { echo json_encode(['success'=>false]); exit; }
    $name    = trim($_POST['name'] ?? '');
    $subtype = $_POST['subtype'] ?? 'bank';
    if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
    $lastCode = $pdo->query("SELECT MAX(CAST(account_code AS UNSIGNED)) FROM accounts WHERE account_subtype IN ('bank','cash') AND NOT is_system")->fetchColumn() ?: 1009;
    $groupId  = $subtype === 'cash'
        ? $pdo->query("SELECT id FROM account_groups WHERE group_name='Cash in Hand' LIMIT 1")->fetchColumn()
        : $pdo->query("SELECT id FROM account_groups WHERE group_name='Bank Accounts' LIMIT 1")->fetchColumn();
    $pdo->prepare("INSERT INTO accounts (account_code,account_name,account_type,account_subtype,group_id,current_balance) VALUES (?,?,'asset',?,?,0)")
        ->execute([$lastCode+1, $name, $subtype, $groupId]);
    $id = $pdo->lastInsertId();
    echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: salaries.php'); exit;
    }
    $action = $_POST['action'] ?? '';

    if ($action === 'save_salary') {
        $month       = $_POST['salary_month'];
        $empName     = trim($_POST['employee_name']);
        $designation = trim($_POST['designation'] ?? '');
        $basic       = (float)$_POST['basic_salary'];
        $allowances  = (float)($_POST['allowances'] ?? 0);
        $deductions  = (float)($_POST['deductions'] ?? 0);
        $net         = $basic + $allowances - $deductions;

        $pdo->prepare("INSERT INTO salaries (salary_month,employee_name,designation,basic_salary,allowances,deductions,net_salary,status,created_by)
                       VALUES (?,?,?,?,?,?,?,'pending',?)")
            ->execute([$month,$empName,$designation,$basic,$allowances,$deductions,$net,currentUserId()]);
        setFlash('success','Salary record added.');
        header('Location: salaries.php'); exit;
    }

    if ($action === 'pay_salary') {
        $salaryId = (int)$_POST['salary_id'];
        $paidFrom = (int)$_POST['paid_from'];
        $paidDate = $_POST['paid_date'];
        $payMode  = $_POST['payment_mode'];

        $stmt = $pdo->prepare("SELECT * FROM salaries WHERE id=?");
        $stmt->execute([$salaryId]); $sal = $stmt->fetch();
        if (!$sal || $sal['status'] === 'paid') {
            setFlash('danger','Already paid or not found.'); header('Location: salaries.php'); exit;
        }

        try {
            $pdo->beginTransaction();
            $salaryExpAcc = $pdo->query("SELECT id FROM accounts WHERE account_code='5200' LIMIT 1")->fetchColumn();
            $journalId = createJournalEntry($paidDate, 'salary',
                "Salary paid to {$sal['employee_name']} for {$sal['salary_month']}",
                [
                    ['account_id' => $salaryExpAcc, 'debit' => $sal['net_salary'], 'credit' => 0],
                    ['account_id' => $paidFrom,      'debit' => 0, 'credit' => $sal['net_salary']],
                ], 'salary', $salaryId, currentUserId()
            );
            $pdo->prepare("UPDATE salaries SET status='paid',paid_from=?,paid_date=?,payment_mode=?,journal_id=? WHERE id=?")
                ->execute([$paidFrom,$paidDate,$payMode,$journalId,$salaryId]);
            $pdo->commit();
            setFlash('success','Salary paid and journal entry created.');
        } catch (Exception $e) {
            $pdo->rollBack();
            setFlash('danger','Error: '.$e->getMessage());
        }
        header('Location: salaries.php'); exit;
    }
}

$month = $_GET['month'] ?? date('Y-m');
$stmt = $pdo->prepare("SELECT * FROM salaries WHERE salary_month=? ORDER BY employee_name");
$stmt->execute([$month]); $salaries = $stmt->fetchAll();
$totalNet = array_sum(array_column($salaries, 'net_salary'));
$totalPaid = array_sum(array_column(array_filter($salaries, fn($s) => $s['status']==='paid'), 'net_salary'));

$bankAccounts = $pdo->query("SELECT id, account_name, current_balance FROM accounts WHERE account_subtype IN ('bank','cash') AND is_active=1 ORDER BY account_code")->fetchAll();
$csrf = generateCSRFToken();
$pageTitle = 'Salaries';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0">Salaries</h2></div>
    <div class="flex gap-8">
        <a href="index.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <button class="btn btn-primary" onclick="document.getElementById('addSalModal').classList.add('show')"><?= icon('plus') ?> Add Employee Salary</button>
    </div>
</div>

<div class="card" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:center;flex-wrap:wrap;">
        <div class="form-group mb-0">
            <label class="text-sm">Month</label>
            <input type="month" name="month" value="<?= $month ?>" style="width:160px;">
        </div>
        <button class="btn btn-primary" style="align-self:flex-end;"><?= icon('filter') ?> View</button>
        <div style="margin-left:auto;" class="flex gap-16">
            <span class="text-sm">Total: <strong class="mono"><?= formatMoney($totalNet) ?></strong></span>
            <span class="text-sm text-success">Paid: <strong class="mono"><?= formatMoney($totalPaid) ?></strong></span>
            <span class="text-sm text-danger">Pending: <strong class="mono"><?= formatMoney($totalNet - $totalPaid) ?></strong></span>
        </div>
    </form>
</div>

<div class="card">
    <?php if ($salaries): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Employee</th><th>Designation</th><th>Basic</th><th>Allowances</th><th>Deductions</th><th class="text-right">Net Salary</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($salaries as $s): ?>
            <tr>
                <td><strong><?= sanitize($s['employee_name']) ?></strong></td>
                <td><?= sanitize($s['designation'] ?? '-') ?></td>
                <td class="num"><?= formatMoney($s['basic_salary']) ?></td>
                <td class="num text-success">+ <?= formatMoney($s['allowances']) ?></td>
                <td class="num text-danger">- <?= formatMoney($s['deductions']) ?></td>
                <td class="num mono"><strong><?= formatMoney($s['net_salary']) ?></strong></td>
                <td><span class="badge badge-<?= $s['status']==='paid'?'success':'warning' ?>"><?= ucfirst($s['status']) ?></span></td>
                <td>
                    <?php if ($s['status'] === 'pending'): ?>
                    <button class="btn btn-sm btn-success" onclick='showPaySalary(<?= json_encode($s) ?>)'><?= icon('cash') ?> Pay</button>
                    <?php else: ?>
                    <span class="text-sm text-muted">Paid <?= formatDate($s['paid_date']) ?></span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('users') ?> No salary records for <?= $month ?>. Add employee salaries above.</div>
    <?php endif; ?>
</div>

<!-- Add Salary Modal -->
<div id="addSalModal" class="modal">
    <div class="modal-box" style="max-width:520px;">
        <div class="modal-header">
            <span>Add Salary Record</span>
            <button class="btn btn-icon" onclick="document.getElementById('addSalModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="save_salary">
            <div class="form-grid">
                <div class="form-group">
                    <label>Month <span class="req">*</span></label>
                    <input type="month" name="salary_month" value="<?= $month ?>" required>
                </div>
                <div class="form-group">
                    <label>Employee Name <span class="req">*</span></label>
                    <input type="text" name="employee_name" required placeholder="Full name">
                </div>
                <div class="form-group">
                    <label>Designation</label>
                    <input type="text" name="designation" placeholder="e.g. Sales Executive">
                </div>
                <div class="form-group">
                    <label>Basic Salary <span class="req">*</span></label>
                    <input type="number" step="0.01" name="basic_salary" required placeholder="0.00" oninput="calcNet()">
                </div>
                <div class="form-group">
                    <label>Allowances</label>
                    <input type="number" step="0.01" name="allowances" value="0" oninput="calcNet()">
                </div>
                <div class="form-group">
                    <label>Deductions (PF/ESI etc.)</label>
                    <input type="number" step="0.01" name="deductions" value="0" oninput="calcNet()">
                </div>
                <div class="form-group full">
                    <div style="background:var(--color-surface-2);padding:10px;border-radius:var(--radius-md);">
                        Net Salary: <strong class="mono" id="netDisplay">0.00</strong>
                    </div>
                </div>
            </div>
            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('addSalModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save</button>
            </div>
        </form>
    </div>
</div>

<!-- Pay Salary Modal -->
<div id="paySalModal" class="modal">
    <div class="modal-box" style="max-width:460px;">
        <div class="modal-header">
            <span>Pay Salary</span>
            <button class="btn btn-icon" onclick="document.getElementById('paySalModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="pay_salary">
            <input type="hidden" name="salary_id" id="pay_sal_id">
            <div id="paySalInfo" style="background:var(--color-surface-2);padding:12px;border-radius:var(--radius-md);margin-bottom:16px;"></div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Pay Date <span class="req">*</span></label>
                    <input type="date" name="paid_date" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="form-group">
                    <label>Pay From <span class="req">*</span></label>
                    <div class="flex gap-8">
                        <select name="paid_from" id="salBankSel" required style="flex:1;">
                            <option value="">-- Select Account --</option>
                            <?php foreach ($bankAccounts as $acc): ?>
                            <option value="<?= $acc['id'] ?>"><?= sanitize($acc['account_name']) ?> (<?= formatMoney($acc['current_balance']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                        <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                            onclick="toggleSalRow('newSalBankRow')" title="Add bank account"><?= icon('plus') ?></button>
                    </div>
                    <div id="newSalBankRow" style="display:none;margin-top:6px;" class="flex gap-8">
                        <input type="text" id="newSalBankName" placeholder="e.g. HDFC Current Account" style="flex:1;">
                        <select id="newSalBankType" style="width:100px;">
                            <option value="bank">Bank</option>
                            <option value="cash">Cash</option>
                        </select>
                        <button type="button" class="btn btn-sm btn-primary" onclick="quickAddSalBank()">Add</button>
                        <button type="button" class="btn btn-sm" onclick="toggleSalRow('newSalBankRow')">Cancel</button>
                    </div>
                </div>
                <div class="form-group full">
                    <label>Payment Mode</label>
                    <select name="payment_mode">
                        <option value="Bank Transfer">Bank Transfer</option>
                        <option value="Cash">Cash</option>
                        <option value="UPI">UPI</option>
                        <option value="Cheque">Cheque</option>
                    </select>
                </div>
            </div>
            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('paySalModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-success"><?= icon('cash') ?> Confirm Payment</button>
            </div>
        </form>
    </div>
</div>

<script>
const CSRF_SAL = '<?= $csrf ?>';
function calcNet() {
    const basic = parseFloat(document.querySelector('[name=basic_salary]').value)||0;
    const allow = parseFloat(document.querySelector('[name=allowances]').value)||0;
    const ded   = parseFloat(document.querySelector('[name=deductions]').value)||0;
    document.getElementById('netDisplay').textContent = (basic+allow-ded).toFixed(2);
}
function showPaySalary(sal) {
    document.getElementById('pay_sal_id').value = sal.id;
    document.getElementById('paySalInfo').innerHTML =
        `<strong>${sal.employee_name}</strong> &mdash; ${sal.salary_month}<br>Net Salary: <strong class="mono">Rs.${parseFloat(sal.net_salary).toFixed(2)}</strong>`;
    document.getElementById('paySalModal').classList.add('show');
}
function toggleSalRow(id) {
    const el = document.getElementById(id);
    el.style.display = el.style.display === 'none' ? 'flex' : 'none';
}
async function quickAddSalBank() {
    const name = document.getElementById('newSalBankName').value.trim();
    const subtype = document.getElementById('newSalBankType').value;
    if (!name) { alert('Enter account name.'); return; }
    const fd = new FormData();
    fd.append('csrf_token', CSRF_SAL);
    fd.append('name', name);
    fd.append('subtype', subtype);
    const r = await fetch('?ajax=quick_add', {method:'POST',body:fd}).then(r=>r.json());
    if (!r.success) { alert(r.error || 'Failed'); return; }
    const sel = document.getElementById('salBankSel');
    sel.appendChild(new Option(r.name + ' (Rs.0.00)', r.id, true, true));
    sel.value = r.id;
    document.getElementById('newSalBankName').value = '';
    toggleSalRow('newSalBankRow');
}
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
