<?php
session_start();
session_write_close();
ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

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

if (!$isAdmin) {
    http_response_code(403);
    ob_clean();
    echo json_encode(['error' => 'You do not have permission to edit employee payroll setup.']);
    exit;
}

$action = $_REQUEST['action'] ?? '';

// ---------------------------------------------------------------------
// Shared payload builder: gross salary, rent profile, resolved component rows
// ---------------------------------------------------------------------
function buildEmployeePayrollPayload(mysqli $conn, array $employee): array
{
    $employeeId = (int) $employee['id'];
    $groupId = $employee['group_id'] ? (int) $employee['group_id'] : null;

    $componentRows = [];
    $allComponents = $conn->query("SELECT * FROM payroll_pay_components WHERE is_statutory = 0 ORDER BY display_order ASC, name ASC");
    while ($comp = $allComponents->fetch_assoc()) {
        $cid = $comp['id'];
        $amount = 0;
        $active = (int) $comp['is_default'] === 1;
        $sourceLabel = $comp['is_default'] ? 'Default' : 'Not assigned';

        if ($groupId) {
            $gStmt = $conn->prepare("SELECT amount, is_active FROM group_pay_components WHERE group_id = ? AND component_id = ?");
            $gStmt->bind_param('ii', $groupId, $cid);
            $gStmt->execute();
            $gRow = $gStmt->get_result()->fetch_assoc();
            $gStmt->close();
            if ($gRow) {
                $amount = $gRow['amount'];
                $active = (int) $gRow['is_active'] === 1;
                $sourceLabel = 'Pay Group';
            }
        }

        $eStmt = $conn->prepare("SELECT amount, is_active FROM employee_pay_components WHERE employee_id = ? AND component_id = ?");
        $eStmt->bind_param('ii', $employeeId, $cid);
        $eStmt->execute();
        $eRow = $eStmt->get_result()->fetch_assoc();
        $eStmt->close();
        if ($eRow) {
            $amount = $eRow['amount'];
            $active = (int) $eRow['is_active'] === 1;
            $sourceLabel = 'Individual Override';
        }

        $componentRows[] = [
            'component_id' => (int) $cid,
            'name' => $comp['name'],
            'type' => $comp['type'],
            'is_pct' => $comp['calculation_type'] === 'percentage_of_gross',
            'percentage_value' => $comp['percentage_value'],
            'amount' => (float) $amount,
            'active' => $active,
            'source' => $sourceLabel,
        ];
    }

    $rentStmt = $conn->prepare("SELECT * FROM employee_tax_profile WHERE employee_id = ?");
    $rentStmt->bind_param('i', $employeeId);
    $rentStmt->execute();
    $rentProfile = $rentStmt->get_result()->fetch_assoc() ?: null;
    $rentStmt->close();
    if ($rentProfile && !empty($rentProfile['updated_at'])) {
        $rentProfile['updated_at'] = date('d M Y H:i', strtotime($rentProfile['updated_at']));
    }

    $grossStmt = $conn->prepare("SELECT * FROM employee_salary_base WHERE employee_id = ?");
    $grossStmt->bind_param('i', $employeeId);
    $grossStmt->execute();
    $grossProfile = $grossStmt->get_result()->fetch_assoc() ?: null;
    $grossStmt->close();
    if ($grossProfile && !empty($grossProfile['updated_at'])) {
        $grossProfile['updated_at'] = date('d M Y H:i', strtotime($grossProfile['updated_at']));
    }

    return [
        'components' => $componentRows,
        'rent' => $rentProfile,
        'gross' => $grossProfile,
    ];
}

// ---------------------------------------------------------------------
// action=search_employees -- live search-as-you-type for the employee picker
// ---------------------------------------------------------------------
if ($action === 'search_employees') {
    $q = trim($_GET['q'] ?? '');
    $like = '%' . $q . '%';

    if ($q === '') {
        $stmt = $conn->prepare("SELECT id, employee_no, name, designation FROM employees ORDER BY name ASC LIMIT 20");
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("
            SELECT id, employee_no, name, designation
            FROM employees
            WHERE name LIKE ? OR employee_no LIKE ? OR designation LIKE ?
            ORDER BY name ASC LIMIT 20
        ");
        $stmt->bind_param('sss', $like, $like, $like);
        $stmt->execute();
    }
    $res = $stmt->get_result();
    $rows = [];
    while ($r = $res->fetch_assoc()) { $rows[] = $r; }
    $stmt->close();

    ob_clean();

    echo json_encode(['results' => $rows]);
    exit;
}

// ---------------------------------------------------------------------
// action=load_employee -- everything needed to render one employee's panel
// ---------------------------------------------------------------------
if ($action === 'load_employee') {
    $employeeId = (int) ($_GET['employee_id'] ?? 0);

    $stmt = $conn->prepare("SELECT id, employee_no, name, designation, group_id FROM employees WHERE id = ?");
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $employee = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$employee) {
        http_response_code(404);
        ob_clean();
        echo json_encode(['error' => 'Employee not found.']);
        exit;
    }

    ob_clean();

    echo json_encode(['employee' => $employee] + buildEmployeePayrollPayload($conn, $employee));
    exit;
}

// ---------------------------------------------------------------------
// action=save_gross_salary -- store gross salary, auto-fill % components
// ---------------------------------------------------------------------
if ($action === 'save_gross_salary' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $employeeId = (int) ($_POST['employee_id'] ?? 0);
    $annualGross = (float) ($_POST['annual_gross_salary'] ?? 0);

    $stmt = $conn->prepare("
        INSERT INTO employee_salary_base (employee_id, annual_gross_salary, updated_by)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE annual_gross_salary = VALUES(annual_gross_salary), updated_by = VALUES(updated_by)
    ");
    $stmt->bind_param('idi', $employeeId, $annualGross, $_SESSION['user_id']);
    $stmt->execute();
    $stmt->close();

    $monthlyGross = $annualGross / 12;
    $pctComponents = $conn->query("SELECT id, percentage_value FROM payroll_pay_components WHERE calculation_type = 'percentage_of_gross' AND is_statutory = 0 AND is_active = 1");
    $filled = 0;
    while ($pc = $pctComponents->fetch_assoc()) {
        $computedAmount = round($monthlyGross * ((float) $pc['percentage_value'] / 100), 2);
        $fillStmt = $conn->prepare("
            INSERT INTO employee_pay_components (employee_id, component_id, amount, is_active, updated_by)
            VALUES (?, ?, ?, 1, ?)
            ON DUPLICATE KEY UPDATE amount = VALUES(amount), updated_by = VALUES(updated_by)
        ");
        $fillStmt->bind_param('iidi', $employeeId, $pc['id'], $computedAmount, $_SESSION['user_id']);
        $fillStmt->execute();
        $fillStmt->close();
        $filled++;
    }

    $stmt = $conn->prepare("SELECT id, employee_no, name, designation, group_id FROM employees WHERE id = ?");
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $employee = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $message = $filled > 0
        ? "Annual gross salary saved, and $filled percentage-based component(s) auto-calculated from it."
        : "Annual gross salary saved. No components are currently set to calculate from gross.";

    ob_clean();

    echo json_encode(['message' => $message, 'employee' => $employee] + buildEmployeePayrollPayload($conn, $employee));
    exit;
}

// ---------------------------------------------------------------------
// action=save_components -- save each component's amount/active state
// ---------------------------------------------------------------------
if ($action === 'save_components' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $employeeId = (int) ($_POST['employee_id'] ?? 0);
    $componentIds = $_POST['component_id'] ?? [];

    foreach ($componentIds as $componentId) {
        $componentId = (int) $componentId;
        $amount = (float) ($_POST['amount_' . $componentId] ?? 0);
        $isActive = isset($_POST['active_' . $componentId]) ? 1 : 0;

        $stmt = $conn->prepare("
            INSERT INTO employee_pay_components (employee_id, component_id, amount, is_active, updated_by)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE amount = VALUES(amount), is_active = VALUES(is_active), updated_by = VALUES(updated_by)
        ");
        $stmt->bind_param('iidii', $employeeId, $componentId, $amount, $isActive, $_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT id, employee_no, name, designation, group_id FROM employees WHERE id = ?");
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $employee = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    ob_clean();

    echo json_encode(['message' => 'Payroll components updated for this employee.', 'employee' => $employee] + buildEmployeePayrollPayload($conn, $employee));
    exit;
}

// ---------------------------------------------------------------------
// action=save_rent -- save annual rent paid (for PAYE rent relief)
// ---------------------------------------------------------------------
if ($action === 'save_rent' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $employeeId = (int) ($_POST['employee_id'] ?? 0);
    $annualRent = (float) ($_POST['annual_rent_paid'] ?? 0);
    $reference = trim($_POST['rent_receipt_reference'] ?? '');

    $stmt = $conn->prepare("
        INSERT INTO employee_tax_profile (employee_id, annual_rent_paid, rent_receipt_reference, updated_by)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE annual_rent_paid = VALUES(annual_rent_paid), rent_receipt_reference = VALUES(rent_receipt_reference), updated_by = VALUES(updated_by)
    ");
    $stmt->bind_param('idsi', $employeeId, $annualRent, $reference, $_SESSION['user_id']);
    $stmt->execute();
    $stmt->close();

    $stmt = $conn->prepare("SELECT id, employee_no, name, designation, group_id FROM employees WHERE id = ?");
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $employee = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    ob_clean();

    echo json_encode(['message' => 'Annual rent paid updated for this employee.', 'employee' => $employee] + buildEmployeePayrollPayload($conn, $employee));
    exit;
}

http_response_code(400);
ob_clean();
echo json_encode(['error' => 'Unknown action.']);