<?php
/**
 * MJPOS -> MJ ERP Hub: Employee Summary Endpoint
 * Drop at: api/erp/employee-summary.php inside MJPOS project root
 *
 * Returns ONE snapshot row for the "to" date - headcount doesn't vary daily,
 * and payroll is a period total (this month's paid payroll), not a per-day figure.
 *
 * GET /api/erp/employee-summary.php?from=2026-07-23&to=2026-07-30
 * Response:
 * { "status": "success", "data": [
 *     { "period_date": "2026-07-30", "employee_count": 3, "total_payroll": 45600.00 }
 * ]}
 */

require_once __DIR__ . '/erp_auth.php';
require_once __DIR__ . '/../../mjpos/config/config.php'; // MJPOS app lives in the 'mjpos' subfolder

erp_require_auth();
list($from, $to) = erp_get_date_range();

try {
    // Confirmed: `employees` table, status enum('active','inactive','terminated')
    $countStmt = erp_pdo()->query("SELECT COUNT(*) AS c FROM employees WHERE status = 'active'");
    $employeeCount = (int)($countStmt->fetch(PDO::FETCH_ASSOC)['c'] ?? 0);

    // Confirmed: `payroll_records` table, net_salary + payment_status + paid_at
    // Sums payroll actually PAID within the requested date range.
    $payrollStmt = erp_pdo()->prepare(
        "SELECT SUM(net_salary) AS total
         FROM payroll_records
         WHERE payment_status = 'paid'
           AND DATE(paid_at) BETWEEN ? AND ?"
    );
    $payrollStmt->execute([$from, $to]);
    $payrollTotal = (float)($payrollStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0);

    $rows = [[
        'period_date' => $to,
        'employee_count' => $employeeCount,
        'total_payroll' => $payrollTotal,
    ]];

    erp_json_success($rows);

} catch (Exception $e) {
    erp_json_error('Query failed: ' . $e->getMessage(), 500);
}
