<?php

namespace App\Controllers;

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

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

        $teacherModel = new Teacher();
        
        $params = [
            'search' => $_GET['search'] ?? '',
            'status_filter' => $_GET['status_filter'] ?? '',
        ];

        $teachers = $teacherModel->search($params);
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Our Teachers';
        
        $editingTeacher = null;
        if (isset($_GET['edit_id'])) {
            $editingTeacher = $teacherModel->find($_GET['edit_id']);
        }

        $viewingTeacher = null;
        if (isset($_GET['view_id'])) {
            $viewingTeacher = $teacherModel->find($_GET['view_id']);
        }

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

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $teacherModel = new Teacher();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'phone' => $_POST['phone'] ?: null,
                'email' => $_POST['email'] ?: null,
                'subject' => $_POST['subject'] ?: null,
                'status' => $_POST['status'] ?? 'Active',
            ];

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

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

        if (isset($_GET['id'])) {
            $teacherModel = new Teacher();
            $teacherModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Teacher profile removed.', 'type' => 'info'];
        }
        redirect('/admin/teachers');
        exit;
    }
}
