<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Course;
use App\Models\Category;
use App\Models\FeeHead;
use App\Models\Setting;

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

        $courseModel = new Course();
        $params = [
            'search' => $_GET['search'] ?? '',
            'filter_category' => $_GET['filter_category'] ?? '',
        ];

        $courses = $courseModel->search($params);
        
        $categoryModel = new Category();
        $categories = $categoryModel->search(['filter_status' => 1]);

        $feeHeadModel = new FeeHead();
        $feeHeads = $feeHeadModel->search(['filter_status' => 1]);
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Our Courses';
        
        $editingCourse = null;
        if (isset($_GET['edit_id'])) {
            $editingCourse = $courseModel->find($_GET['edit_id']);
        }

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

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $courseModel = new Course();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'category' => $_POST['category'],
                'duration_months' => $_POST['duration_months'],
                'status' => $_POST['status'] ?? 'Active',
            ];

            $fees = [];
            if (isset($_POST['fees']) && is_array($_POST['fees'])) {
                foreach ($_POST['fees'] as $fee) {
                    if (!empty($fee['fee_type']) && isset($fee['amount'])) {
                        $fees[] = $fee;
                    }
                }
            }

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

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

        if (isset($_GET['id'])) {
            $courseModel = new Course();
            $courseModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Course deleted successfully.', 'type' => 'info'];
        }
        redirect('/admin/courses');
        exit;
    }
}
