<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Admission Controller
 *
 * Handles the student admission form display and submission.
 */
class AdmissionController extends Controller
{
    /**
     * Display the admission form with course and branch dropdowns.
     *
     * @return void
     */
    public function index(): void
    {
        $courseModel = $this->model('Course');
        $branchModel = $this->model('Branch');
        $settingModel = $this->model('Setting');

        $courses = $courseModel->where('active', 1);
        $branches = $branchModel->where('active', 1);
        $settings = $settingModel->getAll();

        $this->view('admission/index', [
            'title'      => 'Admission - Gmind Institute',
            'courses'    => $courses,
            'branches'   => $branches,
            'settings'   => $settings,
            'currentPage' => 'admission',
        ]);
    }

    /**
     * Process the admission form submission.
     *
     * Validates CSRF token, sanitizes inputs, creates a user account,
     * and inserts a student enrollment record.
     *
     * @return void
     */
    public function store(): void
    {
        $this->validateCsrf();

        $name          = sanitize($_POST['name'] ?? '');
        $email         = sanitize($_POST['email'] ?? '');
        $phone         = sanitize($_POST['phone'] ?? '');
        $password      = $_POST['password'] ?? '';
        $courseId      = (int) ($_POST['course_id'] ?? 0);
        $branchId      = (int) ($_POST['branch_id'] ?? 0);
        $dob           = sanitize($_POST['dob'] ?? '');
        $address       = sanitize($_POST['address'] ?? '');
        $guardianName  = sanitize($_POST['guardian_name'] ?? '');
        $guardianPhone = sanitize($_POST['guardian_phone'] ?? '');

        // Basic validation
        if (empty($name) || empty($email) || empty($password) || $courseId <= 0 || $branchId <= 0) {
            flash('error', 'Please fill in all required fields.');
            redirect('/admission');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect('/admission');
        }

        if (strlen($password) < 6) {
            flash('error', 'Password must be at least 6 characters long.');
            redirect('/admission');
        }

        // Check if email already exists
        $userModel = $this->model('User');
        $existingUser = $userModel->getByEmail($email);

        if ($existingUser !== null) {
            flash('error', 'An account with this email already exists. Please login instead.');
            redirect('/login');
        }

        try {
            // Create user account
            $userId = $userModel->createStudent([
                'name'     => $name,
                'email'    => $email,
                'password' => $password,
                'phone'    => $phone,
            ]);

            // Generate enrollment number
            $enrollmentNo = 'GM' . date('Y') . str_pad((string) $userId, 5, '0', STR_PAD_LEFT);

            // Create student record
            $studentModel = $this->model('Student');
            $studentModel->create([
                'user_id'        => $userId,
                'enrollment_no'  => $enrollmentNo,
                'course_id'      => $courseId,
                'branch_id'      => $branchId,
                'dob'            => $dob ?: null,
                'address'        => $address,
                'guardian_name'  => $guardianName,
                'guardian_phone' => $guardianPhone,
                'status'         => 'active',
            ]);

            flash('success', 'Admission submitted successfully! Your enrollment number is ' . $enrollmentNo);
            redirect('/login');
        } catch (\Throwable $e) {
            error_log('Admission error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect('/admission');
        }
    }
}
