<?php
require_once "db.php";

header('Content-Type: application/json');

$employee_id  = (int)($_GET['employee_id'] ?? 0);
$salary_month = $_GET['salary_month'] ?? '';

if (!$employee_id || !$salary_month) {
    echo json_encode(['success' => false]);
    exit;
}

/* ======================
   BASE SALARY
====================== */
$empRes = $conn->query("
    SELECT base_salary 
    FROM employees 
    WHERE employee_id = $employee_id
");

if (!$empRes || $empRes->num_rows === 0) {
    echo json_encode(['success' => false]);
    exit;
}

$base_salary = (float)$empRes->fetch_assoc()['base_salary'];

/* ======================
   ADVANCE (THIS MONTH ONLY)
====================== */
$advRes = $conn->query("
    SELECT IFNULL(SUM(amount),0) AS total_advance
    FROM advance_pay
    WHERE employee_id = $employee_id
    AND DATE_FORMAT(advance_date,'%Y-%m') = '$salary_month'
");

$monthly_advance = (float)$advRes->fetch_assoc()['total_advance'];

/* ======================
   SALARY PAID (THIS MONTH)
====================== */
$salRes = $conn->query("
    SELECT IFNULL(SUM(paid_amount),0) AS total_paid
    FROM salary_pay
    WHERE employee_id = $employee_id
    AND salary_month = '$salary_month'
");

$total_paid = (float)$salRes->fetch_assoc()['total_paid'];

/* ======================
   CALCULATIONS
====================== */
$advance_remaining = max(0, $monthly_advance - $total_paid);

$payable_salary = $base_salary - $monthly_advance - $total_paid;
if ($payable_salary < 0) {
    $payable_salary = 0;
}

echo json_encode([
    'success' => true,
    'base_salary' => $base_salary,
    'advance_remaining' => $advance_remaining,
    'payable_salary' => $payable_salary
]);
