<?php
session_start();

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

if (!isset($_SESSION['userid']) || !in_array($_SESSION['layer'], ['super_admin', 'admin'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

require_once('../../db.php');
require_once('../../shared/functionsinc.php');

$response = [];

try {
    ob_start(); // Start output buffering
    if (isset($_POST['getslots'])) {
        $data = getDealerSlots($pdo);
        $response = $data;
    }

    if (isset($_POST['addslots'])) {
        $dealerId = $_POST['dealer_id'];
        $slots = $_POST['slots'];
        addDealerSlots($pdo, $dealerId, $slots);
        $response = ['success' => 'Slots added successfully'];
    }

    if (isset($_POST['removeslots'])) {
        $dealerId = $_POST['dealer_id'];
        $slots = $_POST['slots'];
        removeDealerSlots($pdo, $dealerId, $slots);
        $response = ['success' => 'Slots removed successfully'];
    }

    if (isset($_POST['getDealerFtpSlots'])) {
        $dealerId = $_POST['dealer_id'];

        $ftpServers = fetchData('ftp_servers', ['active' => 1]);

        $results = [];

        foreach ($ftpServers as $server) {
            $allocation = fetchDataSingle('dealer_ftp_allocations', [
                'dealer_id' => $dealerId,
                'ftp_server_id' => $server['id']
            ]);

            $results[] = [
                'id' => $server['id'],
                'label' => $server['label'],
                'camera_slots_allowed' => $allocation['camera_slots_allowed'] ?? 0,
                'camera_slots_used' => $allocation['camera_slots_used'] ?? 0
            ];
        }

        $response = ['servers' => $results];
    }

    if (isset($_POST['updateDealerCameraSlots'])) {
        $dealerId = (int)($_POST['dealer_id'] ?? 0);
        $slotInputs = $_POST['slots'] ?? [];

        if (!$dealerId || !is_array($slotInputs)) {
            $response = ['error' => 'Missing dealer or slot data'];
        } else {
            foreach ($slotInputs as $ftpServerId => $allowed) {
                $ftpServerId = (int)$ftpServerId;
                $allowed = max(0, (int)$allowed);

                $existing = fetchDataSingle('dealer_ftp_allocations', [
                    'dealer_id' => $dealerId,
                    'ftp_server_id' => $ftpServerId
                ]);

                if ($existing) {
                    updateTable('dealer_ftp_allocations', [
                        'camera_slots_allowed' => $allowed
                    ], 'id = :id', ['id' => $existing['id']]);
                } else {
                    insertData('dealer_ftp_allocations', [
                        'dealer_id' => $dealerId,
                        'ftp_server_id' => $ftpServerId,
                        'camera_slots_allowed' => $allowed,
                        'camera_slots_used' => 0
                    ]);
                }
            }

            $response = ['success' => 'Camera slots updated successfully'];
        }
    }

    if (isset($_POST['getAvailableFtpServers']) && isset($_POST['dealer_id'])) {
        $dealerId = (int)$_POST['dealer_id'];

        $allServers = fetchData('ftp_servers', ['active' => 1]);

        $assigned = fetchData('dealer_ftp_allocations', ['dealer_id' => $dealerId]);
        $assignedIds = array_column($assigned, 'ftp_server_id');

        $available = array_filter($allServers, function ($server) use ($assignedIds) {
            return !in_array($server['id'], $assignedIds);
        });

        $response = ['servers' => array_values($available)];
    }

    $output = ob_get_clean(); // Get output and clean buffer
    if ($output) {
        // If there's any unexpected output, include it in the response for debugging
        $response['debug_output'] = $output;
    }
} catch (Exception $e) {
    $response = ['error' => $e->getMessage()];
}

echo json_encode($response);
