<?php
// finance/payroll.php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../inc/permissions.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../inc/notification_helper.php';
require_once __DIR__ . '/_layout.php';
require_once __DIR__ . '/advance_deductions_helper.php';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$canPermissionManage = has_any_permission(['finance_access', 'payroll_page']);
$canFinanceManage    = function_exists('finance_can_manage') ? finance_can_manage() : false;
$currentEmployeeId   = function_exists('finance_current_employee_id') ? finance_current_employee_id($pdo) : 0;

$role = strtoupper((string)($_SESSION['role'] ?? ''));

$canManage = ($role === 'OWNER') || $canFinanceManage || $canPermissionManage;
$canSharePayroll = ($role === 'OWNER') || $canPermissionManage || $canFinanceManage;

if (!$canManage && $currentEmployeeId <= 0) {
    if (!headers_sent()) {
        http_response_code(403);
    }
    exit('غير مصرح');
}

finance_shell_start('payroll');
page_header('كشف الرواتب');

$branchId = (int)($_SESSION['branch_id'] ?? 1);
$userId   = (int)($_SESSION['user_id'] ?? 0);

$month = (string)($_GET['m'] ?? date('Y-m'));
if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
    $month = date('Y-m');
}

$msg = '';
$err = '';

/* ===== Helpers ===== */
function payroll_table_cols(PDO $pdo, string $table): array
{
    try {
        $st = $pdo->query("SHOW COLUMNS FROM `$table`");
        return $st->fetchAll(PDO::FETCH_COLUMN, 0) ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

function payroll_first_existing(array $cols, array $candidates): ?string
{
    foreach ($candidates as $c) {
        if (in_array($c, $cols, true)) {
            return $c;
        }
    }
    return null;
}

function payroll_emp_name_sql(PDO $pdo, string $alias = 'e'): string
{
    $cols = payroll_table_cols($pdo, 'employees');

    $nameCol = payroll_first_existing($cols, ['full_name', 'name', 'emp_name', 'employee', 'arabic_name', 'first_name']);
    $lastCol = payroll_first_existing($cols, ['last_name', 'family_name']);

    if ($nameCol && $nameCol !== 'first_name') {
        return "NULLIF(TRIM($alias.`$nameCol`),'')";
    }

    if ($nameCol === 'first_name' && $lastCol) {
        return "NULLIF(TRIM(CONCAT(COALESCE($alias.`first_name`,''),' ',COALESCE($alias.`$lastCol`,''))),'')";
    }

    return "CONCAT('EMP#', $alias.id)";
}

/* ===== Detect columns ===== */
$empCols   = payroll_table_cols($pdo, 'employees');
$salCols   = payroll_table_cols($pdo, 'employee_salaries');
$bonusCols = payroll_table_cols($pdo, 'employee_bonuses');
$dedCols   = payroll_table_cols($pdo, 'employee_deductions');
$runCols   = payroll_table_cols($pdo, 'payroll_runs');
$itemCols  = payroll_table_cols($pdo, 'payroll_items');
$userCols  = payroll_table_cols($pdo, 'users');

$empBranchCol = payroll_first_existing($empCols, ['branch_id', 'branch', 'branchId']);
$empNameExpr  = payroll_emp_name_sql($pdo, 'e');

$hasSalaryCurrency = in_array('currency', $salCols, true);
$hasSalaryIsActive = in_array('is_active', $salCols, true);

$hasBonusMonth = in_array('payroll_month', $bonusCols, true);
$bonusDateCol  = in_array('bonus_date', $bonusCols, true)
    ? 'bonus_date'
    : (in_array('created_at', $bonusCols, true) ? 'created_at' : null);

$hasDedMonth = in_array('payroll_month', $dedCols, true);
$dedDateCol  = in_array('deduction_date', $dedCols, true)
    ? 'deduction_date'
    : (in_array('created_at', $dedCols, true) ? 'created_at' : null);

$runHasStatus    = in_array('status', $runCols, true);
$runHasCreatedBy = in_array('created_by', $runCols, true);

$itemHasCurrency = in_array('currency', $itemCols, true);

$empEmailCol = payroll_first_existing($empCols, ['email', 'work_email', 'employee_email', 'personal_email']);
$userEmployeeIdCol = payroll_first_existing($userCols, ['employee_id', 'emp_id']);

/* مهم: هذه الأعمدة تستخدم لاستبعاد سجل السلفة الأصلي من الراتب */
$dedHasSourceType = in_array('source_type', $dedCols, true);
$dedHasSourceId   = in_array('source_id', $dedCols, true);

/* ===== POST actions ===== */
if ($canManage && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $monthP = (string)($_POST['month'] ?? $month);

    if (!preg_match('/^\d{4}-\d{2}$/', $monthP)) {
        $monthP = date('Y-m');
    }

    $from = $monthP . '-01';
    $to   = date('Y-m-t', strtotime($from));

    try {
        if ($action === 'generate') {
            /* 1) أنشئ أقساط السلف الشهرية أولاً */
            $advanceApplyResult = apply_monthly_advance_deductions($pdo, $monthP, $branchId, $userId);

            if ($runHasStatus) {
                $st = $pdo->prepare("SELECT id, status FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
            } else {
                $st = $pdo->prepare("SELECT id, NULL AS status FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
            }
            $st->execute([$monthP, $branchId]);
            $run = $st->fetch(PDO::FETCH_ASSOC) ?: null;

            if (!$run) {
                $fields = ['payroll_month', 'branch_id'];
                $vals   = [$monthP, $branchId];

                if ($runHasStatus) {
                    $fields[] = 'status';
                    $vals[]   = 'DRAFT';
                }

                if ($runHasCreatedBy) {
                    $fields[] = 'created_by';
                    $vals[]   = $userId;
                }

                $fieldList = '`' . implode('`,`', $fields) . '`';
                $ph = implode(',', array_fill(0, count($fields), '?'));

                $st = $pdo->prepare("INSERT INTO payroll_runs ($fieldList) VALUES ($ph)");
                $st->execute($vals);

                $runId = (int)$pdo->lastInsertId();
            } else {
                $runId = (int)$run['id'];

                if ($runHasStatus) {
                    $st = $pdo->prepare("UPDATE payroll_runs SET status = 'DRAFT' WHERE id = ?");
                    $st->execute([$runId]);
                }
            }

            $pdo->beginTransaction();

            $st = $pdo->prepare("DELETE FROM payroll_items WHERE payroll_run_id = ?");
            $st->execute([$runId]);

            if ($empBranchCol) {
                $st = $pdo->prepare("SELECT id FROM employees WHERE `$empBranchCol` = ?");
                $st->execute([$branchId]);
            } else {
                $st = $pdo->query("SELECT id FROM employees");
            }

            $emps = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];

            $itemFields = ['payroll_run_id', 'employee_id', 'basic_salary', 'allowances', 'bonuses', 'deductions', 'net_salary'];
            if ($itemHasCurrency) {
                $itemFields[] = 'currency';
            }

            $itemFieldList = '`' . implode('`,`', $itemFields) . '`';
            $itemPh = implode(',', array_fill(0, count($itemFields), '?'));
            $ins = $pdo->prepare("INSERT INTO payroll_items ($itemFieldList) VALUES ($itemPh)");

            foreach ($emps as $eid) {
                $eid = (int)$eid;

                $curSelect = $hasSalaryCurrency ? "COALESCE(currency,'AED') AS currency" : "'AED' AS currency";

                if ($hasSalaryIsActive) {
                    $st = $pdo->prepare("
                        SELECT
                            COALESCE(basic_salary,0) AS basic_salary,
                            COALESCE(housing_allowance,0) AS housing_allowance,
                            COALESCE(transport_allowance,0) AS transport_allowance,
                            COALESCE(other_allowance,0) AS other_allowance,
                            $curSelect
                        FROM employee_salaries
                        WHERE employee_id = ? AND is_active = 1
                        ORDER BY id DESC
                        LIMIT 1
                    ");
                } else {
                    $st = $pdo->prepare("
                        SELECT
                            COALESCE(basic_salary,0) AS basic_salary,
                            COALESCE(housing_allowance,0) AS housing_allowance,
                            COALESCE(transport_allowance,0) AS transport_allowance,
                            COALESCE(other_allowance,0) AS other_allowance,
                            $curSelect
                        FROM employee_salaries
                        WHERE employee_id = ?
                        ORDER BY id DESC
                        LIMIT 1
                    ");
                }
                $st->execute([$eid]);

                $s = $st->fetch(PDO::FETCH_ASSOC) ?: [
                    'basic_salary'        => 0,
                    'housing_allowance'   => 0,
                    'transport_allowance' => 0,
                    'other_allowance'     => 0,
                    'currency'            => 'AED',
                ];

                $basic = (float)$s['basic_salary'];
                $allow = (float)$s['housing_allowance'] + (float)$s['transport_allowance'] + (float)$s['other_allowance'];
                $cur   = (string)($s['currency'] ?? 'AED');

                if ($hasBonusMonth) {
                    $st = $pdo->prepare("
                        SELECT COALESCE(SUM(amount),0)
                        FROM employee_bonuses
                        WHERE employee_id = ? AND payroll_month = ?
                    ");
                    $st->execute([$eid, $monthP]);
                    $bon = (float)$st->fetchColumn();
                } elseif ($bonusDateCol) {
                    $st = $pdo->prepare("
                        SELECT COALESCE(SUM(amount),0)
                        FROM employee_bonuses
                        WHERE employee_id = ? AND DATE(`$bonusDateCol`) BETWEEN ? AND ?
                    ");
                    $st->execute([$eid, $from, $to]);
                    $bon = (float)$st->fetchColumn();
                } else {
                    $bon = 0.0;
                }

                /* استبعاد سجل السلفة الأصلي source_type=advance فقط */
                if ($hasDedMonth) {
                    if ($dedHasSourceType) {
                        $st = $pdo->prepare("
                            SELECT COALESCE(SUM(amount),0)
                            FROM employee_deductions
                            WHERE employee_id = ?
                              AND payroll_month = ?
                              AND (source_type IS NULL OR source_type <> 'advance')
                        ");
                        $st->execute([$eid, $monthP]);
                    } else {
                        $st = $pdo->prepare("
                            SELECT COALESCE(SUM(amount),0)
                            FROM employee_deductions
                            WHERE employee_id = ?
                              AND payroll_month = ?
                        ");
                        $st->execute([$eid, $monthP]);
                    }
                    $ded = (float)$st->fetchColumn();
                } elseif ($dedDateCol) {
                    if ($dedHasSourceType) {
                        $st = $pdo->prepare("
                            SELECT COALESCE(SUM(amount),0)
                            FROM employee_deductions
                            WHERE employee_id = ?
                              AND DATE(`$dedDateCol`) BETWEEN ? AND ?
                              AND (source_type IS NULL OR source_type <> 'advance')
                        ");
                        $st->execute([$eid, $from, $to]);
                    } else {
                        $st = $pdo->prepare("
                            SELECT COALESCE(SUM(amount),0)
                            FROM employee_deductions
                            WHERE employee_id = ?
                              AND DATE(`$dedDateCol`) BETWEEN ? AND ?
                        ");
                        $st->execute([$eid, $from, $to]);
                    }
                    $ded = (float)$st->fetchColumn();
                } else {
                    $ded = 0.0;
                }

                $net = $basic + $allow + $bon - $ded;
                if ($net < 0) {
                    $net = 0.0;
                }

                $vals = [$runId, $eid, $basic, $allow, $bon, $ded, $net];
                if ($itemHasCurrency) {
                    $vals[] = $cur;
                }

                $ins->execute($vals);
            }

            if (function_exists('audit')) {
                audit($pdo, $userId, 'GENERATE', 'payroll_run', $runId, [
                    'month'     => $monthP,
                    'branch_id' => $branchId,
                    'employees' => count($emps),
                    'advance_installments_created' => (int)($advanceApplyResult['created'] ?? 0),
                ]);
            }

            $pdo->commit();

            $createdInstallments = (int)($advanceApplyResult['created'] ?? 0);
            $msg = 'تم توليد / إعادة توليد كشف الرواتب للشهر ' . $monthP .
                   ' | أقساط السلف المضافة: ' . $createdInstallments;

            if (!empty($advanceApplyResult['errors'])) {
                $err = 'ملاحظات أقساط السلف: ' . implode(' | ', $advanceApplyResult['errors']);
            }

            $month = $monthP;
        }

        elseif ($action === 'finalize') {
            if ($runHasStatus) {
                $st = $pdo->prepare("SELECT id, status FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
                $st->execute([$monthP, $branchId]);
                $run = $st->fetch(PDO::FETCH_ASSOC) ?: null;

                if (!$run) {
                    throw new RuntimeException('لم يتم توليد مسير الرواتب لهذا الشهر بعد');
                }

                $runId = (int)$run['id'];

                if (($run['status'] ?? '') !== 'FINAL') {
                    $st = $pdo->prepare("UPDATE payroll_runs SET status = 'FINAL' WHERE id = ?");
                    $st->execute([$runId]);
                }
            } else {
                $st = $pdo->prepare("SELECT id FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
                $st->execute([$monthP, $branchId]);
                $run = $st->fetch(PDO::FETCH_ASSOC) ?: null;

                if (!$run) {
                    throw new RuntimeException('لم يتم توليد مسير الرواتب لهذا الشهر بعد');
                }

                $runId = (int)$run['id'];
            }

            if (function_exists('audit')) {
                audit($pdo, $userId, 'FINALIZE', 'payroll_run', $runId, [
                    'month'     => $monthP,
                    'branch_id' => $branchId,
                ]);
            }

            $empEmailSql = $empEmailCol
                ? "COALESCE(NULLIF(TRIM(e.`$empEmailCol`), ''), '') AS employee_email"
                : "'' AS employee_email";

            $userJoin = '';
            $userSelect = 'NULL AS app_user_id';
            if ($userEmployeeIdCol) {
                $userJoin = "LEFT JOIN users u ON u.`$userEmployeeIdCol` = e.id";
                $userSelect = "u.id AS app_user_id";
            }

            $itemCurrencySelect = $itemHasCurrency ? "i.currency" : "'AED' AS currency";

            $sqlNotify = "
                SELECT
                    i.employee_id,
                    COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name,
                    $empEmailSql,
                    $userSelect,
                    i.basic_salary,
                    i.allowances,
                    i.bonuses,
                    i.deductions,
                    i.net_salary,
                    $itemCurrencySelect
                FROM payroll_items i
                JOIN employees e ON e.id = i.employee_id
                $userJoin
                WHERE i.payroll_run_id = ?
            ";

            $st = $pdo->prepare($sqlNotify);
            $st->execute([$runId]);
            $notifyRows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

            $salaryMailCount = 0;
            $salaryInAppCount = 0;

            foreach ($notifyRows as $nr) {
                $employeeName   = trim((string)($nr['emp_name'] ?? ''));
                $employeeEmail  = trim((string)($nr['employee_email'] ?? ''));
                $employeeUserId = (int)($nr['app_user_id'] ?? 0);

                $grossSalary = (float)$nr['basic_salary']
                    + (float)$nr['allowances']
                    + (float)$nr['bonuses'];

                $netSalary = (float)$nr['net_salary'];

                if ($employeeUserId > 0 && function_exists('notify_salary_user')) {
                    if (notify_salary_user($pdo, $employeeUserId, $monthP, $netSalary, $grossSalary)) {
                        $salaryInAppCount++;
                    }
                }

                if ($employeeEmail !== '' && function_exists('send_salary_notification_to_employee')) {
                    if (send_salary_notification_to_employee(
                        $employeeEmail,
                        $employeeName !== '' ? $employeeName : 'الموظف',
                        $monthP,
                        $netSalary,
                        $grossSalary
                    )) {
                        $salaryMailCount++;
                    }
                }
            }

            $msg = "تم اعتماد / إعادة اعتماد الكشف. تم إرسال {$salaryMailCount} بريد راتب و {$salaryInAppCount} إشعار داخل النظام.";
            $month = $monthP;
        }

        elseif ($action === 'reopen') {
            if (!$runHasStatus) {
                throw new RuntimeException('جدول payroll_runs لا يحتوي على عمود status');
            }

            $st = $pdo->prepare("SELECT id, status FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
            $st->execute([$monthP, $branchId]);
            $run = $st->fetch(PDO::FETCH_ASSOC) ?: null;

            if (!$run) {
                throw new RuntimeException('لم يتم العثور على كشف هذا الشهر');
            }

            $runId = (int)$run['id'];

            $st = $pdo->prepare("UPDATE payroll_runs SET status = 'DRAFT' WHERE id = ?");
            $st->execute([$runId]);

            if (function_exists('audit')) {
                audit($pdo, $userId, 'REOPEN', 'payroll_run', $runId, [
                    'month'     => $monthP,
                    'branch_id' => $branchId,
                ]);
            }

            $msg = 'تم إلغاء اعتماد الكشف وإعادته إلى DRAFT';
            $month = $monthP;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $err = 'تعذر تنفيذ العملية: ' . $e->getMessage();
    }
}

/* ===== load run + items ===== */
$runId = null;
$status = 'DRAFT';

if ($runHasStatus) {
    $st = $pdo->prepare("SELECT id, status, created_at FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
} else {
    $st = $pdo->prepare("SELECT id, NULL AS status, NULL AS created_at FROM payroll_runs WHERE payroll_month = ? AND branch_id = ? LIMIT 1");
}
$st->execute([$month, $branchId]);

$r = $st->fetch(PDO::FETCH_ASSOC);
if ($r) {
    $runId  = (int)$r['id'];
    $status = (string)($r['status'] ?? 'DRAFT');
}

$items = [];
if ($runId) {
    $params = [$runId];
    $whereExtra = '';

    if (!$canManage) {
        $whereExtra = " AND i.employee_id = ? ";
        $params[] = $currentEmployeeId;
    }

    $sqlItems = "
        SELECT
            i.*,
            COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name
        FROM payroll_items i
        JOIN employees e ON e.id = i.employee_id
        WHERE i.payroll_run_id = ?
        $whereExtra
        ORDER BY emp_name
    ";

    $st = $pdo->prepare($sqlItems);
    $st->execute($params);
    $items = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
?>

<style>
.msg{padding:10px 12px;border-radius:12px;margin:10px 0;border:1px solid #e5e7eb;background:#fff}
.msg.ok{border-color:#bbf7d0;background:#ecfdf5;color:#065f46}
.msg.err{border-color:#fecaca;background:#fff1f2;color:#991b1b}
.table{width:100%;border-collapse:separate;border-spacing:0;overflow:hidden;border-radius:16px}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #eef2f7;text-align:right;font-size:13px;vertical-align:middle}
.table thead th{background:#f8fafc;color:#0f172a;font-weight:700}
.table tr:last-child td{border-bottom:none}
.payroll-pill{
    display:inline-block;
    padding:8px 10px;
    border-radius:999px;
    background:#f1f5f9;
    color:#0f172a;
    border:1px solid #e2e8f0;
    font-size:12px;
}
.note{font-size:12px;color:#64748b;margin-top:6px}
.print-btn{
    border:none;
    background:transparent;
    cursor:pointer;
    font-size:18px;
    line-height:1;
}
.print-btn:hover{opacity:.8}
.actions-row{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
}
.actions-left{
    display:flex;
    align-items:center;
    gap:10px;
    margin-inline-start:auto;
}
.actions-right{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
}
.row-actions{
    display:flex;
    align-items:center;
    gap:8px;
    justify-content:flex-start;
    flex-wrap:wrap;
}
@media print{
    body{background:#fff !important}
    .side,.header,.row,.msg,.note,.pill,.print-col,.actions-card,.no-print{display:none !important}
    .wrap{display:block !important}
    .main{padding:0 !important}
    .card{border:none !important;box-shadow:none !important}
    .table{border-radius:0 !important}
}
</style>

<script>
function printFullPayrollReport() {
    window.print();
}

function buildPayrollMessage(data) {
    return [
        'كشف راتب / Payroll Statement',
        'الموظف: ' + data.employee,
        'الشهر: ' + data.month,
        'الراتب الأساسي: ' + data.basic + ' ' + data.currency,
        'البدلات: ' + data.allowances + ' ' + data.currency,
        'المكافآت: ' + data.bonuses + ' ' + data.currency,
        'الخصومات: ' + data.deductions + ' ' + data.currency,
        'الصافي: ' + data.net + ' ' + data.currency,
        '',
        'تم الإنشاء من نظام HLG Finance'
    ].join('\n');
}

document.addEventListener('click', function (e) {
    const printBtn = e.target.closest('.js-print-payroll');
    if (printBtn) {
        const employee   = printBtn.dataset.employee || '';
        const basic      = printBtn.dataset.basic || '0.00';
        const allowances = printBtn.dataset.allowances || '0.00';
        const bonuses    = printBtn.dataset.bonuses || '0.00';
        const deductions = printBtn.dataset.deductions || '0.00';
        const net        = printBtn.dataset.net || '0.00';
        const currency   = printBtn.dataset.currency || 'AED';
        const month      = printBtn.dataset.month || '';

        const win = window.open('', '_blank', 'width=900,height=700');
        if (!win) {
            alert('المتصفح منع نافذة الطباعة. اسمح بالنوافذ المنبثقة ثم أعد المحاولة.');
            return;
        }

        const html = `
        <!doctype html>
        <html lang="ar" dir="rtl">
        <head>
            <meta charset="utf-8">
            <title>كشف راتب - ${employee}</title>
            <style>
                body{font-family:Arial,sans-serif;direction:rtl;margin:30px;color:#0f172a}
                .head{border-bottom:2px solid #e5e7eb;margin-bottom:20px;padding-bottom:10px}
                .title{font-size:24px;font-weight:bold;color:#0f172a}
                .sub{font-size:14px;color:#64748b;margin-top:6px}
                table{width:100%;border-collapse:collapse;margin-top:20px}
                th,td{border:1px solid #ddd;padding:12px;text-align:right;font-size:14px}
                th{background:#f8fafc}
                .net{margin-top:20px;font-size:22px;font-weight:bold;color:#0f172a}
                .foot{margin-top:35px;font-size:13px;color:#64748b}
            </style>
        </head>
        <body>
            <div class="head">
                <div class="title">كشف راتب / Payroll Statement</div>
                <div class="sub">الشهر: ${month}</div>
                <div class="sub">الموظف: ${employee}</div>
            </div>

            <table>
                <tr><th>الراتب الأساسي</th><td>${basic} ${currency}</td></tr>
                <tr><th>البدلات</th><td>${allowances} ${currency}</td></tr>
                <tr><th>المكافآت</th><td>${bonuses} ${currency}</td></tr>
                <tr><th>الخصومات</th><td>${deductions} ${currency}</td></tr>
            </table>

            <div class="net">الصافي: ${net} ${currency}</div>
            <div class="foot">تم إنشاء هذا الكشف من نظام HLG Finance.</div>
        </body>
        </html>
        `;

        win.document.open();
        win.document.write(html);
        win.document.close();

        setTimeout(function () {
            win.focus();
            win.print();
        }, 300);

        return;
    }

    const waBtn = e.target.closest('.js-share-whatsapp');
    if (waBtn) {
        const data = {
            employee: waBtn.dataset.employee || '',
            basic: waBtn.dataset.basic || '0.00',
            allowances: waBtn.dataset.allowances || '0.00',
            bonuses: waBtn.dataset.bonuses || '0.00',
            deductions: waBtn.dataset.deductions || '0.00',
            net: waBtn.dataset.net || '0.00',
            currency: waBtn.dataset.currency || 'AED',
            month: waBtn.dataset.month || ''
        };

        const msg = buildPayrollMessage(data);
        window.open('https://wa.me/?text=' + encodeURIComponent(msg), '_blank');
        return;
    }

    const mailBtn = e.target.closest('.js-share-email');
    if (mailBtn) {
        const data = {
            employee: mailBtn.dataset.employee || '',
            basic: mailBtn.dataset.basic || '0.00',
            allowances: mailBtn.dataset.allowances || '0.00',
            bonuses: mailBtn.dataset.bonuses || '0.00',
            deductions: mailBtn.dataset.deductions || '0.00',
            net: mailBtn.dataset.net || '0.00',
            currency: mailBtn.dataset.currency || 'AED',
            month: mailBtn.dataset.month || ''
        };

        const subject = 'Payroll Statement - ' + data.employee + ' - ' + data.month;
        const body = buildPayrollMessage(data);

        window.location.href =
            'mailto:?subject=' + encodeURIComponent(subject) +
            '&body=' + encodeURIComponent(body);

        return;
    }
});
</script>

<?php if ($msg): ?>
    <div class="msg ok"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($err): ?>
    <div class="msg err"><?= h($err) ?></div>
<?php endif; ?>

<div class="card no-print" style="margin-bottom:12px">
    <form method="get" class="row" action="">
        <select class="select" name="m">
            <?php for ($i = 0; $i < 12; $i++): ?>
                <?php
                $m = date('Y-m', strtotime(date('Y-m-01') . " -$i months"));
                $sel = ($m === $month) ? 'selected' : '';
                ?>
                <option <?= $sel ?> value="<?= h($m) ?>"><?= h($m) ?></option>
            <?php endfor; ?>
        </select>
        <button class="btn" type="submit">فتح</button>
    </form>
</div>

<?php if ($canManage): ?>
<div class="card actions-card no-print" style="margin-bottom:12px">
    <h3 style="margin:0 0 10px 0;color:#fff">إجراءات كشف الرواتب</h3>

    <div class="actions-row">
        <div class="actions-right">
            <form method="post" class="row" style="margin:0">
                <input type="hidden" name="month" value="<?= h($month) ?>">
                <button class="btn" name="action" value="generate" type="submit">توليد / إعادة توليد</button>

                <?php if ($status !== 'FINAL'): ?>
                    <button class="btn secondary" name="action" value="finalize" type="submit">اعتماد FINAL</button>
                <?php else: ?>
                    <button class="btn secondary" name="action" value="finalize" type="submit">إعادة اعتماد FINAL</button>
                    <button class="btn secondary" name="action" value="reopen" type="submit">إلغاء الاعتماد</button>
                <?php endif; ?>
            </form>

            <span class="payroll-pill">الحالة: <?= h($status) ?></span>
        </div>

        <div class="actions-left">
            <button type="button" class="btn secondary" onclick="printFullPayrollReport()">🖨 طباعة الكشف كامل</button>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <h3 style="margin:0 0 10px 0;color:#fff">
        <?= $canManage ? 'محتوى الكشف' : 'مستحقاتي في كشف الرواتب' ?>
    </h3>

    <?php if (!$canManage): ?>
        <div class="note">هذه الصفحة تعرض صفك فقط من مسير الرواتب حفاظًا على الخصوصية.</div>
    <?php endif; ?>

    <table class="table">
        <thead>
            <tr>
                <th>الموظف</th>
                <th>أساسي</th>
                <th>بدلات</th>
                <th>مكافآت</th>
                <th>خصومات</th>
                <th>صافي</th>
                <?php if ($canManage): ?>
                    <th class="print-col no-print">الإجراءات</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php if (!$items): ?>
                <tr>
                    <td colspan="<?= $canManage ? '7' : '6' ?>">
                        <?= $runId ? 'لا توجد بيانات' : 'لم يتم توليد الكشف بعد' ?>
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($items as $it): ?>
                    <?php
                    $employeeName = (string)($it['emp_name'] ?? '');
                    $basicV       = number_format((float)($it['basic_salary'] ?? 0), 2);
                    $allowV       = number_format((float)($it['allowances'] ?? 0), 2);
                    $bonusV       = number_format((float)($it['bonuses'] ?? 0), 2);
                    $dedV         = number_format((float)($it['deductions'] ?? 0), 2);
                    $netV         = number_format((float)($it['net_salary'] ?? 0), 2);
                    $currencyV    = (string)($it['currency'] ?? 'AED');
                    ?>
                    <tr>
                        <td><?= h($employeeName) ?></td>
                        <td><?= h($basicV) ?></td>
                        <td><?= h($allowV) ?></td>
                        <td><?= h($bonusV) ?></td>
                        <td><?= h($dedV) ?></td>
                        <td><?= h($netV) ?> <?= h($currencyV) ?></td>

                        <?php if ($canManage): ?>
                            <td class="no-print print-col">
                                <div class="row-actions">
                                    <button
                                        type="button"
                                        class="print-btn js-print-payroll"
                                        title="طباعة كشف الراتب"
                                        data-employee="<?= h($employeeName) ?>"
                                        data-basic="<?= h($basicV) ?>"
                                        data-allowances="<?= h($allowV) ?>"
                                        data-bonuses="<?= h($bonusV) ?>"
                                        data-deductions="<?= h($dedV) ?>"
                                        data-net="<?= h($netV) ?>"
                                        data-currency="<?= h($currencyV) ?>"
                                        data-month="<?= h($month) ?>"
                                    >🖨</button>

                                    <?php if ($canSharePayroll): ?>
                                        <button
                                            type="button"
                                            class="btn secondary js-share-whatsapp"
                                            data-employee="<?= h($employeeName) ?>"
                                            data-basic="<?= h($basicV) ?>"
                                            data-allowances="<?= h($allowV) ?>"
                                            data-bonuses="<?= h($bonusV) ?>"
                                            data-deductions="<?= h($dedV) ?>"
                                            data-net="<?= h($netV) ?>"
                                            data-currency="<?= h($currencyV) ?>"
                                            data-month="<?= h($month) ?>"
                                        >واتساب</button>

                                        <button
                                            type="button"
                                            class="btn secondary js-share-email"
                                            data-employee="<?= h($employeeName) ?>"
                                            data-basic="<?= h($basicV) ?>"
                                            data-allowances="<?= h($allowV) ?>"
                                            data-bonuses="<?= h($bonusV) ?>"
                                            data-deductions="<?= h($dedV) ?>"
                                            data-net="<?= h($netV) ?>"
                                            data-currency="<?= h($currencyV) ?>"
                                            data-month="<?= h($month) ?>"
                                        >بريد</button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php finance_shell_end(); ?>