<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');
$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

function ensure_admin_sal(){ if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403); }

function ym_bounds($y,$m){ $first=sprintf('%04d-%02d-01',$y,$m); $last=date('Y-m-t', strtotime($first)); return [$first,$last]; }

switch ($action) {
  case 'list':
    $month = isset($_GET['month']) ? (int)$_GET['month'] : null;
    $year = isset($_GET['year']) ? (int)$_GET['year'] : null;
    if ($month && $year) {
      [$from,$to]=ym_bounds($year,$month);
      $stmt=$mysqli->prepare('SELECT a.id, a.adv_date, a.amount, a.notes, e.full_name AS employee_name, a.employee_id FROM salary_advances a LEFT JOIN employees e ON e.id=a.employee_id WHERE a.adv_date BETWEEN ? AND ? ORDER BY a.adv_date DESC, a.id DESC');
      $stmt->bind_param('ss',$from,$to); $stmt->execute(); $res=$stmt->get_result();
    } else {
      $res = $mysqli->query('SELECT a.id, a.adv_date, a.amount, a.notes, e.full_name AS employee_name, a.employee_id FROM salary_advances a LEFT JOIN employees e ON e.id=a.employee_id ORDER BY a.adv_date DESC, a.id DESC');
    }
    $data=[]; while($r=$res->fetch_assoc()){ $data[]=$r; }
    json_response(['data'=>$data]);
    break;
  case 'create':
    ensure_admin_sal(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $employee_id=(int)($_POST['employee_id'] ?? 0); $adv_date=$_POST['adv_date'] ?? ''; $amount=(float)($_POST['amount'] ?? 0); $notes=trim($_POST['notes'] ?? '');
    if(!$employee_id || !$adv_date || !$amount) json_response(['message'=>'Missing fields'],400);
    $stmt=$mysqli->prepare('INSERT INTO salary_advances (employee_id, adv_date, amount, notes) VALUES (?,?,?,?)');
    $stmt->bind_param('isds',$employee_id,$adv_date,$amount,$notes);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Created']);
    break;
  case 'delete':
    ensure_admin_sal(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    $stmt=$mysqli->prepare('DELETE FROM salary_advances WHERE id=?');
    $stmt->bind_param('i',$id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Deleted']);
    break;
  default:
    json_response(['message'=>'Invalid action'],400);
}
