<?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 pay group setup.']);
    exit;
}

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

function buildGroupComponentRows(mysqli $conn, int $groupId): array
{
    $rows = [];
    $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;

        $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;
        }

        $rows[] = [
            '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,
        ];
    }
    return $rows;
}

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

    if ($q === '') {
        $stmt = $conn->prepare("
            SELECT g.id, g.name, (SELECT COUNT(*) FROM employees e WHERE e.group_id = g.id) as employee_count
            FROM groups g ORDER BY g.name ASC LIMIT 20
        ");
        $stmt->execute();
    } else {
        $stmt = $conn->prepare("
            SELECT g.id, g.name, (SELECT COUNT(*) FROM employees e WHERE e.group_id = g.id) as employee_count
            FROM groups g WHERE g.name LIKE ? ORDER BY g.name ASC LIMIT 20
        ");
        $stmt->bind_param('s', $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_group -- component rows for one pay group
// ---------------------------------------------------------------------
if ($action === 'load_group') {
    $groupId = (int) ($_GET['group_id'] ?? 0);

    $stmt = $conn->prepare("SELECT g.*, (SELECT COUNT(*) FROM employees e WHERE e.group_id = g.id) as employee_count FROM groups g WHERE g.id = ?");
    $stmt->bind_param('i', $groupId);
    $stmt->execute();
    $group = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    ob_clean();

    echo json_encode(['group' => $group, 'components' => buildGroupComponentRows($conn, $groupId)]);
    exit;
}

// ---------------------------------------------------------------------
// action=save_components -- save each component's amount/active state for the group
// ---------------------------------------------------------------------
if ($action === 'save_components' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $groupId = (int) ($_POST['group_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 group_pay_components (group_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', $groupId, $componentId, $amount, $isActive, $_SESSION['user_id']);
        $stmt->execute();
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT g.*, (SELECT COUNT(*) FROM employees e WHERE e.group_id = g.id) as employee_count FROM groups g WHERE g.id = ?");
    $stmt->bind_param('i', $groupId);
    $stmt->execute();
    $group = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    ob_clean();

    echo json_encode([
        'message' => 'Pay group components updated. Individual employee overrides still take priority.',
        'group' => $group,
        'components' => buildGroupComponentRows($conn, $groupId),
    ]);
    exit;
}

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