<?php

namespace App\Controllers;

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

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

        $materialModel = new StudyMaterial();
        $params = [
            'search' => $_GET['search'] ?? '',
            'filter_course' => $_GET['filter_course'] ?? '',
            'filter_type' => $_GET['filter_type'] ?? '',
        ];

        $materials = $materialModel->search($params);
        
        $courseModel = new Course();
        $courses = $courseModel->search();

        $batchModel = new Batch();
        $batches = $batchModel->search();
        
        $settingModel = new Setting();
        $siteSettings = $settingModel->getAll();
        
        $title = 'Study Materials';
        
        $editingMaterial = null;
        if (isset($_GET['edit_id'])) {
            $editingMaterial = $materialModel->find($_GET['edit_id']);
        }

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

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

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $materialModel = new StudyMaterial();
            
            $data = [
                'id' => $_POST['id'] ?? null,
                'title' => $_POST['title'],
                'description' => $_POST['description'] ?: null,
                'course_id' => $_POST['course_id'] ?: null,
                'batch_id' => $_POST['batch_id'] ?: null,
                'type' => $_POST['type'] ?? 'file',
                'file_path' => $_POST['existing_file_path'] ?? null,
                'link_url' => $_POST['link_url'] ?: null,
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            // Handle File Upload
            if ($data['type'] === 'file' && isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../../public/uploads/materials/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                
                $fileName = time() . '_' . basename($_FILES['file']['name']);
                if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $fileName)) {
                    $data['file_path'] = '/uploads/materials/' . $fileName;
                    $data['link_url'] = null;
                }
            }

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

    public function toggleStatus() {
        if (!Auth::hasPermission('materials')) {
            redirect('/login');
            exit;
        }
        if (isset($_GET['id'])) {
            $materialModel = new StudyMaterial();
            $materialModel->toggleStatus($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Material status updated!', 'type' => 'info'];
        }
        redirect('/admin/study-materials');
        exit;
    }

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

        if (isset($_GET['id'])) {
            $materialModel = new StudyMaterial();
            $material = $materialModel->find($_GET['id']);
            if ($material && $material['file_path']) {
                $filePath = __DIR__ . '/../../public' . $material['file_path'];
                if (file_exists($filePath)) unlink($filePath);
            }
            $materialModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Material deleted successfully.', 'type' => 'info'];
        }
        redirect('/admin/study-materials');
        exit;
    }
}
