<?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['full_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'] ?? '');
        $message       = sanitize($_POST['message'] ?? '');

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

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect(BASE_PATH . '/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(BASE_PATH . '/login');
        }

        // Auto-generate password if not provided (admission form doesn't have password field)
        if (empty($password)) {
            $password = 'Gmind@' . random_int(100000, 999999);
        }

        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(BASE_PATH . '/login');
        } catch (\Throwable $e) {
            error_log('Admission error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect(BASE_PATH . '/admission');
        }
    }
}
