<?php
// finance/bonuses.php (FULL FIXED + aligned actions column + working edit/print/delete)
declare(strict_types=1);
require_once __DIR__ . '/../inc/permissions.php';

require_once __DIR__ . '/_layout.php';

$canPermissionManage = has_any_permission(['finance_access', 'bonuses.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'] ?? ''));

/* الإدارة لمن لديه:
   - OWNER
   - أو صلاحية المالية الأساسية
   - أو صلاحية القسم/الصفحة من نظام permissions.php
*/
$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('bonuses');
page_header('المكافآت');

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

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

/* ===== Helpers ===== */
function bonuses_table_cols(PDO $pdo, string $table): array {
  $st = $pdo->query("SHOW COLUMNS FROM `$table`");
  return $st->fetchAll(PDO::FETCH_COLUMN, 0) ?: [];
}
function bonuses_first_existing(array $cols, array $candidates): ?string {
  foreach ($candidates as $c) {
    if (in_array($c, $cols, true)) return $c;
  }
  return null;
}
function bonuses_emp_name_sql(PDO $pdo, string $alias='e'): string {
  $cols = bonuses_table_cols($pdo, 'employees');

  $nameCol = bonuses_first_existing($cols, ['full_name','name','emp_name','employee','arabic_name','first_name']);
  $lastCol = bonuses_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   = bonuses_table_cols($pdo, 'employees');
$bonusCols = bonuses_table_cols($pdo, 'employee_bonuses');

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

$hasId         = in_array('id', $bonusCols, true);
$hasCreatedBy  = in_array('created_by', $bonusCols, true);
$hasCreatedAt  = in_array('created_at', $bonusCols, true);
$hasPayrollMon = in_array('payroll_month', $bonusCols, true);
$hasBonusDate  = in_array('bonus_date', $bonusCols, true);
$hasReason     = in_array('reason', $bonusCols, true);

/* ===== 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['bonus_date'] ?? ''));

    if (!$hasBonusDate) $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 ($hasBonusDate) {
          $fields[] = 'bonus_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_bonuses ($fieldList) VALUES ($ph)");
        $st->execute($vals);

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

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

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

    if ($bonusId <= 0 || $amount <= 0) {
      $err = 'بيانات التعديل غير مكتملة';
    } else {
      try {
        $st = $pdo->prepare("
          SELECT b.id
          FROM employee_bonuses b
          JOIN employees e ON e.id = b.employee_id
          WHERE b.id = ? " . ($empBranchCol ? "AND e.`$empBranchCol` = ?" : "") . "
          LIMIT 1
        ");
        $paramsCheck = [$bonusId];
        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 ($hasBonusDate) {
          if ($date !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            $date = date('Y-m-d');
          }
          $sets[] = 'bonus_date=?';
          $vals[] = ($date !== '' ? $date : null);

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

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

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

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

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

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

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

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

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

        $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)) : '';

  $st = $pdo->prepare("
    SELECT
      e.id,
      COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name
    FROM employees e
    $whereSqlEmp
    ORDER BY emp_name ASC
  ");
  $st->execute($paramsEmp);
  $employees = $st->fetchAll() ?: [];
}

/* ===== Bonuses list ===== */
$params = [];
$whereSql = '';

if ($canManage) {
  $where = [];
  if ($empBranchCol) {
    $where[] = "e.`$empBranchCol`=?";
    $params[] = $branchId;
  }
  $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
} else {
  $whereSql = "WHERE b.employee_id = ?";
  $params[] = $currentEmployeeId;
}

$dateSelect = $hasBonusDate
  ? "b.bonus_date"
  : ($hasCreatedAt ? "DATE(b.created_at) AS bonus_date" : "NULL AS bonus_date");

$monthSelect = $hasPayrollMon
  ? "b.payroll_month"
  : ($hasCreatedAt ? "DATE_FORMAT(b.created_at, '%Y-%m') AS payroll_month" : "'' AS payroll_month");

$idSelect = $hasId ? "b.id," : "";

$sqlRows = "
SELECT
  $idSelect
  $dateSelect,
  $monthSelect,
  b.amount,
  " . ($hasReason ? "b.reason" : "NULL AS reason") . ",
  COALESCE($empNameExpr, CONCAT('EMP#', e.id)) AS emp_name
FROM employee_bonuses b
JOIN employees e ON e.id = b.employee_id
$whereSql
ORDER BY " . ($hasId ? "b.id" : "emp_name") . " DESC
LIMIT 50
";

$st = $pdo->prepare($sqlRows);
$st->execute($params);
$rows = $st->fetchAll() ?: [];
?>

<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;
}

.icon-btn{
  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:#fff;border-radius:18px;padding:18px;border:1px solid #e5e7eb;
  box-shadow:0 20px 40px rgba(0,0,0,.18);
}
.modal-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}
.modal-title{font-weight:700;color:#fff}
.close-btn{
  border:none;background:#f1f5f9;border-radius:10px;padding:8px 10px;cursor:pointer
}

</style>

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

function printBonusRow(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 #fff;margin-bottom:20px;padding-bottom:10px}
      .title{font-size:24px;font-weight:bold;color:#fff}
      .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_bonus_id');
    const amountEl = document.getElementById('edit_amount');
    const dateEl = document.getElementById('edit_bonus_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) {
    printBonusRow(
      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">
    <input type="hidden" name="action" value="create">

    <select class="select" name="employee_id" required>
      <option value="">اختر موظف</option>
      <?php foreach($employees as $e): ?>
        <option value="<?= (int)$e['id'] ?>"><?= h((string)$e['emp_name']) ?></option>
      <?php endforeach; ?>
    </select>

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

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

    <input class="input" name="reason" placeholder="السبب (اختياري)" style="min-width:260px">
    <button class="btn" type="submit">إضافة</button>
  </form>
</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['bonus_date'] ?? '');
            $rEmp   = (string)$r['emp_name'];
            $rAmt   = number_format((float)$r['amount'], 2);
            $rMonth = (string)($r['payroll_month'] ?? '');
            $rRes   = (string)($r['reason'] ?? '');
          ?>
          <tr>
            <td><?= h($rDate) ?></td>
            <td><?= h($rEmp) ?></td>
            <td><?= $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="<?= (int)$rid ?>"
                    data-amount="<?= h((string)((float)$r['amount'])) ?>"
                    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="bonus_id" value="<?= (int)$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="bonus_id" id="edit_bonus_id" value="">

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

      <?php if ($hasBonusDate): ?>
        <input class="input" type="date" name="bonus_date" id="edit_bonus_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; ?>

<?php finance_shell_end(); ?>