<?php

use App\Models\Slot;

$slotModel = new Slot();
$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    
    // Handle image upload
    if (!empty($_FILES['image_upload']['name'])) {
        $uploadedImage = uploadImage($_FILES['image_upload']);
        if ($uploadedImage) {
            $data['image'] = $uploadedImage;
        }
    } else {
        // Keep current image if no new upload
        $data['image'] = $data['current_image'] ?? '';
    }
    
    // Get action from form data
    $formAction = $data['action'] ?? $action;
    
    try {
        switch ($formAction) {
            case 'create':
            case 'edit':
                if ($formAction === 'create') {
                    $slotId = $slotModel->create($data);
                    $success = "Slot created successfully!";
                } else {
                    $slotModel->update($id, $data);
                    $slotId = $id;
                    $success = "Slot updated successfully!";
                }
                header("Location: /admin/slots/?action=edit&id=" . $slotId);
                exit;
                break;
                
            case 'delete':
                if ($id) {
                    $slotModel->delete($id);
                    $success = "Slot deleted successfully!";
                    $action = 'list';
                }
                break;
        }
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get data for different actions
switch ($action) {
    case 'create':
    case 'new':
        $slot = [
            'name' => '',
            'image' => '',
            'provider' => '',
            'rtp' => '',
            'demo_url' => ''
        ];
        $action = 'create';
        break;
        
    case 'edit':
        if (!$id) {
            $action = 'list';
            break;
        }
        
        $slot = $slotModel->getById($id);
        if (!$slot) {
            $error = "Slot not found!";
            $action = 'list';
            break;
        }
        break;
        
    case 'list':
    default:
        $slots = $slotModel->getAll();
        $action = 'list';
        break;
}

// Determine which template to use
$template = match($action) {
    'list' => 'admin/slots/list.php',
    'create', 'edit' => 'admin/slots/form.php',
    default => 'admin/slots/list.php'
};

return ViewRender($template, [
    'action' => $action,
    'slots' => $slots ?? [],
    'slot' => $slot ?? null,
    'success' => $success ?? null,
    'error' => $error ?? null
]);