<?php
declare(strict_types=1);

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

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

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

$canPermissionManage = has_any_permission(['finance_access', 'deductions.php_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('deductions');
page_header('الخصومات');

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

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

/* ===== Helpers ===== */
function deductions_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 deductions_first_existing(array $cols, array $candidates): ?string {
    foreach ($candidates as $c) {
        if (in_array($c, $cols, true)) {
            return $c;
        }
    }
    return null;
}

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

    $nameCol = deductions_first_existing($cols, ['full_name', 'name', 'emp_name', 'employee', 'arabic_name', 'first_name']);
    $lastCol = deductions_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  = deductions_table_cols($pdo, 'employees');
$dedCols  = deductions_table_cols($pdo, 'employee_deductions');
$userCols = deductions_table_cols($pdo, 'users');

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

$hasCreatedBy  = in_array('created_by', $dedCols, true);
$hasCreatedAt  = in_array('created_at', $dedCols, true);
$hasPayrollMon = in_array('payroll_month', $dedCols, true);
$hasDedDate    = in_array('deduction_date', $dedCols, true);
$hasReason     = in_array('reason', $dedCols, true);
$hasId         = in_array('id', $dedCols, true);

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

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

    if ($action === 'create') {
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $amount     = (float)($_POST['amount'] ?? 0);
        $reason     = trim((string)($_POST['reason'] ?? ''));
        $date       = trim((string)($_POST['deduction_date'] ?? ''));

        if (!$hasDedDate) {
            $date = '';
        }

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

        $month = '';
        if ($hasPayrollMon) {
            $month = ($date !== '') ? substr($date, 0, 7) : date('Y-m');
        }

        if ($employeeId <= 0 || $amount <= 0) {
            $err = 'اختر موظف وأدخل مبلغ صحيح';
        } else {
            try {
                if ($empBranchCol) {
                    $st = $pdo->prepare("SELECT id FROM employees WHERE id = ? AND `$empBranchCol` = ? LIMIT 1");
                    $st->execute([$employeeId, $branchId]);
                } else {
                    $st = $pdo->prepare("SELECT id FROM employees WHERE id = ? LIMIT 1");
                    $st->execute([$employeeId]);
                }

                if (!$st->fetchColumn()) {
                    throw new RuntimeException('الموظف غير موجود');
                }

                $fields = ['employee_id', 'amount'];
                $vals   = [$employeeId, $amount];

                if ($hasReason) {
                    $fields[] = 'reason';
                    $vals[]   = ($reason !== '' ? $reason : null);
                }

                if ($hasDedDate) {
                    $fields[] = 'deduction_date';
                    $vals[]   = ($date !== '' ? $date : null);
                }

                if ($hasPayrollMon) {
                    $fields[] = 'payroll_month';
                    $vals[]   = ($month !== '' ? $month : date('Y-m'));
                }

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

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

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

                $deductionId = (int)$pdo->lastInsertId();

                if (function_exists('audit')) {
                    audit($pdo, $userId, 'CREATE', 'deduction', $deductionId, [
                        'employee_id' => $employeeId,
                        'amount'      => $amount,
                        'date'        => $date,
                        'month'       => $month,
                        'reason'      => $reason,
                    ]);
                }

                $employeeName   = 'الموظف';
                $employeeEmail  = '';
                $employeeUserId = 0;

                $empNameSelect  = "COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name";
                $empEmailSelect = $empEmailCol
                    ? "COALESCE(NULLIF(TRIM(e.`$empEmailCol`), ''), '') AS emp_email"
                    : "'' AS emp_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";
                }

                $st = $pdo->prepare("
                    SELECT
                        $empNameSelect,
                        $empEmailSelect,
                        $userSelect
                    FROM employees e
                    $userJoin
                    WHERE e.id = ?
                    LIMIT 1
                ");
                $st->execute([$employeeId]);
                $empInfo = $st->fetch(PDO::FETCH_ASSOC) ?: [];

                if ($empInfo) {
                    $employeeName   = trim((string)($empInfo['emp_name'] ?? 'الموظف'));
                    $employeeEmail  = trim((string)($empInfo['emp_email'] ?? ''));
                    $employeeUserId = (int)($empInfo['app_user_id'] ?? 0);
                }

                $reasonText   = $reason !== '' ? $reason : 'خصم يدوي';
                $payrollMonth = $month !== '' ? $month : date('Y-m');

                if ($employeeUserId > 0 && function_exists('notify_deduction_user')) {
                    notify_deduction_user(
                        $pdo,
                        $employeeUserId,
                        $payrollMonth,
                        $amount,
                        $reasonText,
                        0.0,
                        $deductionId
                    );
                }

                if ($employeeEmail !== '' && function_exists('send_deduction_notification_to_employee')) {
                    send_deduction_notification_to_employee(
                        $employeeEmail,
                        $employeeName,
                        $payrollMonth,
                        $amount,
                        $reasonText,
                        0.0
                    );
                }

                $msg = 'تم إضافة الخصم';
            } catch (Throwable $e) {
                $err = 'تعذر الإضافة: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'update' && $hasId) {
        $deductionId = (int)($_POST['deduction_id'] ?? 0);
        $amount      = (float)($_POST['amount'] ?? 0);
        $reason      = trim((string)($_POST['reason'] ?? ''));
        $date        = trim((string)($_POST['deduction_date'] ?? ''));

        if ($deductionId <= 0 || $amount <= 0) {
            $err = 'بيانات التعديل غير مكتملة';
        } else {
            try {
                $st = $pdo->prepare("
                    SELECT d.id
                    FROM employee_deductions d
                    JOIN employees e ON e.id = d.employee_id
                    WHERE d.id = ? " . ($empBranchCol ? "AND e.`$empBranchCol` = ?" : "") . "
                    LIMIT 1
                ");
                $paramsCheck = [$deductionId];
                if ($empBranchCol) {
                    $paramsCheck[] = $branchId;
                }
                $st->execute($paramsCheck);

                if (!$st->fetchColumn()) {
                    throw new RuntimeException('السجل غير موجود');
                }

                $sets = ['amount = ?'];
                $vals = [$amount];

                if ($hasReason) {
                    $sets[] = 'reason = ?';
                    $vals[] = ($reason !== '' ? $reason : null);
                }

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

                    $sets[] = 'deduction_date = ?';
                    $vals[] = ($date !== '' ? $date : null);

                    if ($hasPayrollMon) {
                        $sets[] = 'payroll_month = ?';
                        $vals[] = ($date !== '' ? substr($date, 0, 7) : date('Y-m'));
                    }
                }

                $vals[] = $deductionId;

                $st = $pdo->prepare("UPDATE employee_deductions SET " . implode(',', $sets) . " WHERE id = ?");
                $st->execute($vals);

                if (function_exists('audit')) {
                    audit($pdo, $userId, 'UPDATE', 'deduction', $deductionId, [
                        'amount' => $amount,
                        'reason' => $reason,
                        'date'   => $date,
                    ]);
                }

                $msg = 'تم تعديل الخصم';
            } catch (Throwable $e) {
                $err = 'تعذر التعديل: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'delete' && $hasId) {
        $deductionId = (int)($_POST['deduction_id'] ?? 0);

        if ($deductionId > 0) {
            try {
                $st = $pdo->prepare("
                    SELECT d.id
                    FROM employee_deductions d
                    JOIN employees e ON e.id = d.employee_id
                    WHERE d.id = ? " . ($empBranchCol ? "AND e.`$empBranchCol` = ?" : "") . "
                    LIMIT 1
                ");
                $paramsCheck = [$deductionId];
                if ($empBranchCol) {
                    $paramsCheck[] = $branchId;
                }
                $st->execute($paramsCheck);

                if (!$st->fetchColumn()) {
                    throw new RuntimeException('السجل غير موجود');
                }

                $st = $pdo->prepare("DELETE FROM employee_deductions WHERE id = ?");
                $st->execute([$deductionId]);

                if (function_exists('audit')) {
                    audit($pdo, $userId, 'DELETE', 'deduction', $deductionId, []);
                }

                $msg = 'تم حذف الخصم';
            } catch (Throwable $e) {
                $err = 'تعذر الحذف: ' . $e->getMessage();
            }
        }
    }
}

/* ===== Employees dropdown ===== */
$employees = [];

if ($canManage) {
    $whereEmp  = [];
    $paramsEmp = [];

    if ($empBranchCol) {
        $whereEmp[]  = "e.`$empBranchCol` = ?";
        $paramsEmp[] = $branchId;
    }

    $whereSqlEmp = $whereEmp ? ('WHERE ' . implode(' AND ', $whereEmp)) : '';

    $salCols = deductions_table_cols($pdo, 'employee_salaries');
    $hasSalaryIsActive = in_array('is_active', $salCols, true);

    $salaryJoinCondition = $hasSalaryIsActive
        ? "s.employee_id = e.id AND s.is_active = 1"
        : "s.employee_id = e.id";

    $st = $pdo->prepare("
        SELECT
            e.id,
            COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name,
            COALESCE(s.basic_salary, 0) AS basic_salary,
            COALESCE(s.housing_allowance, 0) AS housing_allowance,
            COALESCE(s.transport_allowance, 0) AS transport_allowance,
            COALESCE(s.other_allowance, 0) AS other_allowance
        FROM employees e
        LEFT JOIN employee_salaries s
            ON $salaryJoinCondition
        $whereSqlEmp
        GROUP BY e.id
        ORDER BY emp_name ASC
    ");
    $st->execute($paramsEmp);
    $employees = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

/* ===== Rows list ===== */
/* أبقِ هذا الجزء إذا كان موجودًا لديك سابقًا، أو استخدمه إذا لم يكن موجودًا */
$rows = [];

$whereRows = [];
$paramsRows = [];

if ($canManage) {
    if ($empBranchCol) {
        $whereRows[]  = "e.`$empBranchCol` = ?";
        $paramsRows[] = $branchId;
    }
} else {
    $whereRows[]  = "d.employee_id = ?";
    $paramsRows[] = $currentEmployeeId;
}

$whereSqlRows = $whereRows ? ('WHERE ' . implode(' AND ', $whereRows)) : '';

$selectDate  = $hasDedDate ? "d.deduction_date" : "NULL AS deduction_date";
$selectMonth = $hasPayrollMon ? "d.payroll_month" : "'' AS payroll_month";
$selectReason = $hasReason ? "d.reason" : "'' AS reason";
$selectId = $hasId ? "d.id" : "0 AS id";

$orderBy = $hasCreatedAt ? "d.created_at DESC" : (($hasId ? "d.id DESC" : "e.id DESC"));

$st = $pdo->prepare("
    SELECT
        $selectId,
        $selectDate,
        $selectMonth,
        $selectReason,
        d.amount,
        COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name
    FROM employee_deductions d
    JOIN employees e ON e.id = d.employee_id
    $whereSqlRows
    ORDER BY $orderBy
");
$st->execute($paramsRows);
$rows = $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}
.note{font-size:12px;color:#64748b;margin-top:6px}

.actions-col{
  text-align:center !important;
  width:260px;
  min-width:260px;
  white-space:nowrap;
}

.actions{
  display:flex;
  flex-wrap:nowrap;
  align-items:center;
  justify-content:center;
  gap:8px;
}

.actions form{
  margin:0;
  display:inline-flex;
}

.icon-btn{
  white-space:nowrap;
  min-width:72px;
  text-align:center;
  border:1px solid #dbe3ee;
  background:#fff;
  color:#0f172a;
  border-radius:10px;
  padding:7px 10px;
  cursor:pointer;
  font-family:inherit;
  font-size:13px;
}
.icon-btn:hover{background:#f8fafc}
.icon-btn.print{border-color:#cbd5e1}
.icon-btn.edit{border-color:#bfdbfe}
.icon-btn.delete{border-color:#fecaca;color:#991b1b}

.top-tools{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px}

@media print{
  .side,.header,.top-tools,.no-print,.actions,form,.msg{display:none !important}
  .wrap{display:block !important}
  .main{padding:0 !important}
  body{background:#fff !important}
  .card{box-shadow:none !important;border:1px solid #ddd !important}
}

.modal{
  position:fixed;
  inset:0;
  background:rgba(15,23,42,.45);
  display:none;
  align-items:center;
  justify-content:center;
  padding:16px;
  z-index:9999;
}
.modal.open{display:flex}
.modal-card{
  width:min(650px,100%);
  background:#ffffff !important;
  border:1px solid #e5e7eb !important;
  border-radius:18px;
  padding:18px;
  box-shadow:0 20px 40px rgba(0,0,0,.18);
  color:#0f172a !important;
}
.modal-card,
.modal-card *{color:#0f172a !important}
.modal-head{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-bottom:12px;
}
.modal-title{
  font-weight:700;
  color:#0f172a !important;
  font-size:18px;
}
.close-btn{
  border:none;
  background:#f1f5f9 !important;
  color:#0f172a !important;
  border-radius:10px;
  padding:8px 10px;
  cursor:pointer;
}
#editModal .input,
#editModal input,
#editModal select,
#editModal textarea{
  background:#ffffff !important;
  color:#111827 !important;
  border:1px solid #d4a82a !important;
  border-radius:14px !important;
  padding:12px 14px !important;
  font-size:15px !important;
}
#editModal input::placeholder,
#editModal textarea::placeholder{
  color:#64748b !important;
  opacity:1 !important;
}
#editModal .input:focus,
#editModal input:focus,
#editModal select:focus,
#editModal textarea:focus{
  outline:none !important;
  border-color:#d4a82a !important;
  box-shadow:0 0 0 3px rgba(212,168,42,.18) !important;
  color:#111827 !important;
}
#editModal .btn{
  font-weight:700 !important;
}
#editModal button[type="submit"]{
  background:#d4a82a !important;
  color:#111827 !important;
  border:none !important;
}
#editModal .row{
  display:flex;
  flex-wrap:wrap;
  gap:12px;
  align-items:center;
}
#editModal .row > *{
  flex:1 1 180px;
}
#editModal input[name="reason"]{
  min-width:260px;
}
.deduction-form-row{
  display:flex;
  flex-wrap:wrap;
  gap:12px;
  align-items:center;
}
.deduction-form-row > *{
  flex:1 1 180px;
}
.deduction-form-row button.btn{
  flex:0 0 auto;
  min-width:110px;
}
.salary-preview-box{
  margin-top:14px;
  padding:14px;
  border:1px solid rgba(255,255,255,.12);
  border-radius:14px;
  background:rgba(255,255,255,.04);
}
.salary-preview-grid{
  display:grid;
  grid-template-columns:repeat(4,minmax(160px,1fr));
  gap:12px;
}
.salary-preview-item{
  background:rgba(255,255,255,.05);
  border:1px solid rgba(255,255,255,.08);
  border-radius:12px;
  padding:12px;
  text-align:center;
}
.salary-label{
  display:block;
  font-size:12px;
  color:#cbd5e1;
  margin-bottom:6px;
}
.salary-preview-item strong{
  display:block;
  font-size:15px;
  color:#fff;
}
@media (max-width: 900px){
  .salary-preview-grid{
    grid-template-columns:repeat(2,minmax(140px,1fr));
  }
}
@media (max-width: 640px){
  .salary-preview-grid{
    grid-template-columns:1fr;
  }
}
</style>

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

function printDeductionRow(employee, amount, month, date, reason) {
  const w = window.open('', '_blank', 'width=900,height=700');
  if (!w) {
    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}
    </style>
  </head>
  <body>
    <div class="head">
      <div class="title">كشف خصم</div>
      <div class="sub">الموظف: ${employee}</div>
    </div>
    <table>
      <tr><th>التاريخ</th><td>${date}</td></tr>
      <tr><th>الشهر</th><td>${month}</td></tr>
      <tr><th>المبلغ</th><td>${amount} AED</td></tr>
      <tr><th>السبب</th><td>${reason || '-'}</td></tr>
    </table>
  </body>
  </html>`;

  w.document.open();
  w.document.write(html);
  w.document.close();
  setTimeout(function(){ w.focus(); w.print(); }, 300);
}

document.addEventListener('click', function(e) {
  const editBtn = e.target.closest('.js-edit-row');
  if (editBtn) {
    const id = editBtn.dataset.id || '';
    const amount = editBtn.dataset.amount || '';
    const date = editBtn.dataset.date || '';
    const reason = editBtn.dataset.reason || '';

    const modal = document.getElementById('editModal');
    const idEl = document.getElementById('edit_deduction_id');
    const amountEl = document.getElementById('edit_amount');
    const dateEl = document.getElementById('edit_deduction_date');
    const reasonEl = document.getElementById('edit_reason');

    if (!modal || !idEl || !amountEl) {
      alert('نافذة التعديل غير موجودة أو المعرفات غير صحيحة.');
      return;
    }

    idEl.value = id;
    amountEl.value = amount;
    if (dateEl) dateEl.value = date;
    if (reasonEl) reasonEl.value = reason;

    modal.classList.add('open');
    return;
  }

  const printBtn = e.target.closest('.js-print-row');
  if (printBtn) {
    printDeductionRow(
      printBtn.dataset.employee || '',
      printBtn.dataset.amount || '0.00',
      printBtn.dataset.month || '',
      printBtn.dataset.date || '',
      printBtn.dataset.reason || ''
    );
    return;
  }

  const closeBtn = e.target.closest('.js-close-modal');
  if (closeBtn) {
    const modal = document.getElementById('editModal');
    if (modal) modal.classList.remove('open');
  }
});
</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; ?>

<?php if ($canManage): ?>
<div class="top-tools no-print">
  <button type="button" class="btn" onclick="printWholePage()">🖨 طباعة الصفحة كاملة</button>
</div>
<?php endif; ?>

<?php if ($canManage): ?>
<div class="card" style="margin-bottom:12px">
  <h3 style="margin:0 0 10px 0;color:#fff">إضافة خصم</h3>

  <form method="post" class="row deduction-form-row">
    <input type="hidden" name="action" value="create">

    <select class="select" name="employee_id" id="employee_id" required>
      <option value="">اختر موظف</option>
      <?php foreach ($employees as $e): ?>
        <?php
          $basic = (float)($e['basic_salary'] ?? 0);
          $allow = (float)($e['housing_allowance'] ?? 0)
                 + (float)($e['transport_allowance'] ?? 0)
                 + (float)($e['other_allowance'] ?? 0);
          $gross = $basic + $allow;
        ?>
        <option
          value="<?= (int)($e['id'] ?? 0) ?>"
          data-basic="<?= h((string)$basic) ?>"
          data-allow="<?= h((string)$allow) ?>"
          data-gross="<?= h((string)$gross) ?>"
        >
          <?= h((string)($e['emp_name'] ?? '')) ?>
        </option>
      <?php endforeach; ?>
    </select>

    <input class="input" type="number" step="0.01" name="amount" id="deduction_amount" placeholder="المبلغ" required>

    <?php if ($hasDedDate): ?>
      <input class="input" type="date" name="deduction_date" value="<?= h(date('Y-m-d')) ?>">
    <?php endif; ?>

    <input class="input" type="text" name="reason" placeholder="السبب (اختياري)" style="min-width:260px">

    <button class="btn" type="submit">إضافة</button>
  </form>

  <div id="salaryPreviewBox" class="salary-preview-box" style="display:none">
    <div class="salary-preview-grid">
      <div class="salary-preview-item">
        <span class="salary-label">الراتب الأساسي</span>
        <strong id="empBasicSalary">0.00 AED</strong>
      </div>
      <div class="salary-preview-item">
        <span class="salary-label">البدلات</span>
        <strong id="empAllowances">0.00 AED</strong>
      </div>
      <div class="salary-preview-item">
        <span class="salary-label">إجمالي الراتب</span>
        <strong id="empGrossSalary">0.00 AED</strong>
      </div>
      <div class="salary-preview-item">
        <span class="salary-label">الصافي بعد الخصم</span>
        <strong id="empNetAfterDeduction">0.00 AED</strong>
      </div>
    </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>
        <?php if ($canManage): ?>
          <th class="no-print actions-col">الإجراءات</th>
        <?php endif; ?>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="<?= $canManage ? '6' : '5' ?>">لا توجد بيانات</td></tr>
      <?php else: ?>
        <?php foreach ($rows as $r): ?>
          <?php
            $rid    = (int)($r['id'] ?? 0);
            $rDate  = (string)($r['deduction_date'] ?? '');
            $rEmp   = (string)($r['emp_name'] ?? '');
            $rAmt   = number_format((float)($r['amount'] ?? 0), 2);
            $rMonth = (string)($r['payroll_month'] ?? '');
            $rRes   = (string)($r['reason'] ?? '');
          ?>
          <tr>
            <td><?= h($rDate) ?></td>
            <td><?= h($rEmp) ?></td>
            <td><?= h($rAmt) ?> AED</td>
            <td><?= h($rMonth) ?></td>
            <td><?= h($rRes) ?></td>

            <?php if ($canManage): ?>
              <td class="no-print actions-col">
                <div class="actions">
                  <button
                    type="button"
                    class="icon-btn edit js-edit-row"
                    data-id="<?= $rid ?>"
                    data-amount="<?= h((string)((float)($r['amount'] ?? 0))) ?>"
                    data-date="<?= h($rDate) ?>"
                    data-reason="<?= h($rRes) ?>"
                  >✏ تعديل</button>

                  <form method="post" onsubmit="return confirm('تأكيد حذف الخصم؟');" style="margin:0">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="deduction_id" value="<?= $rid ?>">
                    <button type="submit" class="icon-btn delete">🗑 حذف</button>
                  </form>

                  <button
                    type="button"
                    class="icon-btn print js-print-row"
                    data-employee="<?= h($rEmp) ?>"
                    data-amount="<?= h($rAmt) ?>"
                    data-month="<?= h($rMonth) ?>"
                    data-date="<?= h($rDate) ?>"
                    data-reason="<?= h($rRes) ?>"
                  >🖨 طباعة</button>
                </div>
              </td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

<?php if ($canManage && $hasId): ?>
<div class="modal" id="editModal">
  <div class="modal-card">
    <div class="modal-head">
      <div class="modal-title">تعديل خصم</div>
      <button type="button" class="close-btn js-close-modal">إغلاق</button>
    </div>

    <form method="post" class="row">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="deduction_id" id="edit_deduction_id" value="">

      <input class="input" type="number" step="0.01" name="amount" id="edit_amount" placeholder="المبلغ" required>

      <?php if ($hasDedDate): ?>
        <input class="input" type="date" name="deduction_date" id="edit_deduction_date">
      <?php endif; ?>

      <input class="input" type="text" name="reason" id="edit_reason" placeholder="السبب (اختياري)" style="min-width:260px">

      <button class="btn" type="submit">حفظ التعديل</button>
    </form>
  </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const employeeSelect = document.getElementById('employee_id');
  const amountInput = document.getElementById('deduction_amount');

  const previewBox = document.getElementById('salaryPreviewBox');
  const basicEl = document.getElementById('empBasicSalary');
  const allowEl = document.getElementById('empAllowances');
  const grossEl = document.getElementById('empGrossSalary');
  const netEl = document.getElementById('empNetAfterDeduction');

  function money(val) {
    return parseFloat(val || 0).toFixed(2) + ' AED';
  }

  function updateSalaryPreview() {
    if (!employeeSelect) return;

    const selected = employeeSelect.options[employeeSelect.selectedIndex];
    if (!selected || !selected.value) {
      if (previewBox) previewBox.style.display = 'none';
      return;
    }

    const basic = parseFloat(selected.dataset.basic || '0');
    const allow = parseFloat(selected.dataset.allow || '0');
    const gross = parseFloat(selected.dataset.gross || '0');
    const deduction = amountInput ? parseFloat(amountInput.value || '0') : 0;
    const netAfter = gross - deduction;

    if (basicEl) basicEl.textContent = money(basic);
    if (allowEl) allowEl.textContent = money(allow);
    if (grossEl) grossEl.textContent = money(gross);
    if (netEl) netEl.textContent = money(netAfter);

    if (previewBox) previewBox.style.display = 'block';

    if (amountInput) {
      if (deduction > gross && gross > 0) {
        amountInput.style.borderColor = '#ef4444';
      } else {
        amountInput.style.borderColor = '';
      }
    }
  }

  if (employeeSelect) employeeSelect.addEventListener('change', updateSalaryPreview);
  if (amountInput) amountInput.addEventListener('input', updateSalaryPreview);

  updateSalaryPreview();
});
</script>

<?php finance_shell_end(); ?>