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

require_once __DIR__ . '/_layout.php';

$canManage = function_exists('finance_can_manage') ? finance_can_manage() : false;
$currentEmployeeId = function_exists('finance_current_employee_id') ? finance_current_employee_id($pdo) : 0;

if (!$canManage && $currentEmployeeId <= 0) {
  if (!headers_sent()) http_response_code(403);
  exit('غير مصرح');
}
$userId   = (int)($_SESSION['user_id'] ?? 0);
$allowedBranches = [
  1 => 'فرع أبوظبي',
  2 => 'فرع دبي',
];

if ($canManage && isset($_GET['branch_id'])) {
  $newBranchId = (int)$_GET['branch_id'];

  if (isset($allowedBranches[$newBranchId])) {
    $_SESSION['branch_id'] = $newBranchId;
  }

  header('Location: salaries.php');
  exit;
}

$branchId = (int)($_SESSION['branch_id'] ?? 1);
if (!isset($allowedBranches[$branchId])) {
  $branchId = 1;
  $_SESSION['branch_id'] = 1;
}

$branchName = $allowedBranches[$branchId] ?? 'فرع أبوظبي';
$msg = '';
$err = '';

finance_shell_start('salaries');
page_header('الرواتب والبدلات');


function salaries_table_cols(PDO $pdo, string $table): array {
  $st = $pdo->query("SHOW COLUMNS FROM `$table`");
  return $st->fetchAll(PDO::FETCH_COLUMN, 0) ?: [];
}

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

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

  $nameCol = salaries_first_existing($cols, ['full_name','name','emp_name','employee','arabic_name','first_name']);
  $lastCol = salaries_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)";
}

$empCols = salaries_table_cols($pdo, 'employees');
$salCols = salaries_table_cols($pdo, 'employee_salaries');

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

$hasIsActive     = in_array('is_active', $salCols, true);
$hasEffFrom      = in_array('effective_from', $salCols, true);
$hasEffTo        = in_array('effective_to', $salCols, true);
$hasCreatedBy    = in_array('created_by', $salCols, true);
$hasTotalSalary  = in_array('total_salary', $salCols, true);

if ($canManage && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $employeeId = (int)($_POST['employee_id'] ?? 0);

  $basic = (float)($_POST['basic_salary'] ?? 0);
  $house = (float)($_POST['housing_allowance'] ?? 0);
  $trans = (float)($_POST['transport_allowance'] ?? 0);
  $other = (float)($_POST['other_allowance'] ?? 0);

  $totalInput  = trim((string)($_POST['total_salary'] ?? ''));
  $totalSalary = ($totalInput !== '') ? (float)$totalInput : ($basic + $house + $trans + $other);

  $eff = trim((string)($_POST['effective_from'] ?? ''));

  if ($employeeId <= 0) {
    $err = 'اختر موظف';
  } else {
    try {
      $pdo->beginTransaction();

      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('الموظف غير موجود');
      }

      if ($hasIsActive) {
        $sql = "UPDATE employee_salaries SET is_active=0";
        if ($hasEffTo) {
          $sql .= ", effective_to=CURDATE()";
        }
        $sql .= " WHERE employee_id=? AND is_active=1";

        $st = $pdo->prepare($sql);
        $st->execute([$employeeId]);
      }

      $fields = [
        'employee_id',
        'basic_salary',
        'housing_allowance',
        'transport_allowance',
        'other_allowance'
      ];

      $vals = [
        $employeeId,
        $basic,
        $house,
        $trans,
        $other
      ];

      if ($hasTotalSalary) {
        $fields[] = 'total_salary';
        $vals[]   = $totalSalary;
      }

      if ($hasEffFrom) {
        $fields[] = 'effective_from';
        $vals[]   = ($eff !== '' ? $eff : null);
      }

      if ($hasIsActive) {
        $fields[] = 'is_active';
        $vals[]   = 1;
      }

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

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

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

      if (function_exists('audit')) {
        audit($pdo, $userId, 'CREATE', 'salary', (int)$pdo->lastInsertId(), [
          'employee_id'    => $employeeId,
          'basic'          => $basic,
          'housing'        => $house,
          'transport'      => $trans,
          'other'          => $other,
          'total_salary'   => $totalSalary,
          'effective_from' => $eff,
        ]);
      }

      $pdo->commit();
      $msg = 'تم حفظ الراتب بنجاح';

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

$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() ?: [];
}

$params = [];
$whereSql = '';

if ($canManage) {
  $where = [];

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

  $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
} else {
  $whereSql = "WHERE e.id = ?";
  $params[] = $currentEmployeeId;
}

$effSelect = $hasEffFrom ? "s.effective_from" : "NULL AS effective_from";

$totalSelect = $hasTotalSalary
  ? "COALESCE(s.total_salary, COALESCE(s.basic_salary,0) + COALESCE(s.housing_allowance,0) + COALESCE(s.transport_allowance,0) + COALESCE(s.other_allowance,0)) AS total_salary"
  : "(COALESCE(s.basic_salary,0) + COALESCE(s.housing_allowance,0) + COALESCE(s.transport_allowance,0) + COALESCE(s.other_allowance,0)) AS total_salary";

$sqlRows = "
SELECT
  e.id AS employee_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,
  $totalSelect,
  $effSelect
FROM employees e
LEFT JOIN (
  SELECT s1.*
  FROM employee_salaries s1
  INNER JOIN (
    SELECT employee_id, MAX(id) AS max_id
    FROM employee_salaries
    GROUP BY employee_id
  ) m ON m.employee_id = s1.employee_id AND m.max_id = s1.id
) s ON s.employee_id = e.id
$whereSql
ORDER BY emp_name ASC
";

$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}
.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}
.salary-total{font-weight:800;color:#0f766e}
.branch-switcher{
  display:flex;
  flex-wrap:wrap;
  align-items:center;
  gap:10px;
  margin:0 0 14px 0;
  padding:12px;
  border-radius:18px;
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.12);
}

.branch-btn{
  text-decoration:none;
  padding:10px 16px;
  border-radius:14px;
  font-size:13px;
  font-weight:800;
  color:#fff;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.16);
}

.branch-btn.active{
  background:linear-gradient(135deg,#d4af37,#f5d26b);
  color:#111827;
  border-color:rgba(212,175,55,.85);
  box-shadow:0 10px 25px rgba(212,175,55,.22);
}

.branch-current{
  padding:10px 14px;
  border-radius:14px;
  color:#fff;
  background:rgba(0,0,0,.18);
  font-size:13px;
  font-weight:800;
}
</style>

<?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="branch-switcher">
    <a class="branch-btn <?= $branchId === 1 ? 'active' : '' ?>" href="salaries.php?branch_id=1">
      فرع أبوظبي
    </a>

    <a class="branch-btn <?= $branchId === 2 ? 'active' : '' ?>" href="salaries.php?branch_id=2">
      فرع دبي
    </a>

    <span class="branch-current">
      الفرع الحالي: <?= h($branchName) ?>
    </span>
  </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">
    <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']) ?> (<?= (int)$e['id'] ?>)
        </option>
      <?php endforeach; ?>
    </select>

    <input class="input" type="number" step="0.01" min="0" name="basic_salary" placeholder="الراتب الأساسي" required>
    <input class="input" type="number" step="0.01" min="0" name="housing_allowance" placeholder="بدل سكن">
    <input class="input" type="number" step="0.01" min="0" name="transport_allowance" placeholder="بدل مواصلات">
    <input class="input" type="number" step="0.01" min="0" name="other_allowance" placeholder="بدلات أخرى">

    <input class="input" type="number" step="0.01" min="0" name="total_salary" placeholder="الراتب الإجمالي">

    <?php if ($hasEffFrom): ?>
      <input class="input" type="date" name="effective_from" placeholder="تاريخ السريان">
    <?php endif; ?>

    <button class="btn" type="submit">حفظ</button>
  </form>

  <?php if (!$hasTotalSalary): ?>
    <div class="note">
      تنبيه: لا يوجد عمود total_salary في جدول employee_salaries، لذلك سيتم عرض الإجمالي بالحساب التلقائي فقط.
    </div>
  <?php endif; ?>
</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>
        <th>السريان</th>
      </tr>
    </thead>

    <tbody>
      <?php if (!$rows): ?>
        <tr>
          <td colspan="7">لا توجد بيانات</td>
        </tr>
      <?php else: ?>
        <?php foreach ($rows as $r): ?>
          <?php
            $basic = (float)($r['basic_salary'] ?? 0);
            $house = (float)($r['housing_allowance'] ?? 0);
            $trans = (float)($r['transport_allowance'] ?? 0);
            $other = (float)($r['other_allowance'] ?? 0);
            $tot   = (float)($r['total_salary'] ?? ($basic + $house + $trans + $other));
          ?>
          <tr>
            <td><?= h((string)$r['emp_name']) ?></td>
            <td><?= number_format($basic, 2) ?></td>
            <td><?= number_format($house, 2) ?></td>
            <td><?= number_format($trans, 2) ?></td>
            <td><?= number_format($other, 2) ?></td>
            <td class="salary-total"><?= number_format($tot, 2) ?></td>
            <td><?= h((string)($r['effective_from'] ?? '')) ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

<?php finance_shell_end(); ?>