<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Batch;
use App\Models\Course;
use App\Models\Teacher;
use App\Models\Setting;

class BatchController {
    public function index() {
        if (!Auth::hasPermission('batches')) {
            redirect('/login');
            exit;
        }

        $batchModel = new Batch();
        $params = [
            'search' => $_GET['search'] ?? '',
            'filter_course' => $_GET['filter_course'] ?? '',
            'filter_status' => $_GET['filter_status'] ?? '',
        ];

        $batches = $batchModel->search($params);
        
        $courseModel = new Course();
        $courses = $courseModel->search(['filter_status' => 'Active']);

        $teacherModel = new Teacher();
        $teachers_list = $teacherModel->search(['status_filter' => 'Active']);
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Batches Management';
        
        $editingBatch = null;
        if (isset($_GET['edit_id'])) {
            $editingBatch = $batchModel->find($_GET['edit_id']);
        }

        require_once __DIR__ . '/../../views/admin/batches.php';
    }

    public function save() {
        if (!Auth::hasPermission('batches')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $batchModel = new Batch();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'course_id' => $_POST['course_id'],
                'teacher_id' => $_POST['teacher_id'],
                'start_time' => $_POST['start_time'],
                'end_time' => $_POST['end_time'],
                'days' => isset($_POST['days']) ? implode(',', $_POST['days']) : '',
                'capacity' => $_POST['capacity'],
                'status' => $_POST['status'] ?? 'Upcoming',
            ];

            try {
                $batchModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Batch updated!' : 'Batch created!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/batches');
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('batches')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $batchModel = new Batch();
            $batchModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Batch record removed.', 'type' => 'info'];
        }
        redirect('/admin/batches');
        exit;
    }
}
