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

switch ($action) {
  case 'list':
    $res = $mysqli->query('SELECT d.id, d.ded_date, d.amount, d.reason, e.full_name AS employee_name, d.employee_id FROM salary_deductions d LEFT JOIN employees e ON e.id=d.employee_id ORDER BY d.ded_date DESC, d.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); $ded_date=$_POST['ded_date'] ?? ''; $amount=(float)($_POST['amount'] ?? 0); $reason=trim($_POST['reason'] ?? '');
    if(!$employee_id || !$ded_date || !$amount) json_response(['message'=>'Missing fields'],400);
    $stmt=$mysqli->prepare('INSERT INTO salary_deductions (employee_id, ded_date, amount, reason) VALUES (?,?,?,?)');
    $stmt->bind_param('isds',$employee_id,$ded_date,$amount,$reason);
    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_deductions 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);
}
