<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Profile Controller
 *
 * Handles the student profile view and update functionality.
 */
class ProfileController extends Controller
{
    /**
     * Display the student profile page.
     *
     * @return void
     */
    public function index(): void
    {
        requireLogin();

        $userId = $_SESSION['user_id'] ?? null;
        if ($userId === null) {
            redirect(BASE_PATH . '/login');
        }

        // Get user info
        $userModel = $this->model('User');
        $user = $userModel->find((int) $userId);

        // Get student record if exists
        $studentModel = $this->model('Student');
        $student = $studentModel->getByUserId((int) $userId);

        // Get settings
        $settingModel = $this->model('Setting');
        $settings = $settingModel->getAll();

        $this->view('auth/profile', [
            'title'       => 'My Profile - Gmind Institute',
            'currentPage' => 'profile',
            'user'        => $user,
            'student'     => $student,
            'settings'    => $settings,
        ]);
    }

    /**
     * Update the student profile.
     *
     * Handles profile updates including name, phone, and photo.
     *
     * @return void
     */
    public function update(): void
    {
        requireLogin();

        $this->validateCsrf();

        $userId = $_SESSION['user_id'] ?? null;
        if ($userId === null) {
            redirect(BASE_PATH . '/login');
        }

        $name  = sanitize($_POST['name'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');

        if (empty($name)) {
            flash('error', 'Name is required.');
            redirect(BASE_PATH . '/profile');
        }

        try {
            $userModel = $this->model('User');
            $userModel->updateProfile((int) $userId, [
                'name'  => $name,
                'phone' => $phone,
            ]);

            // Update session name
            $_SESSION['user_name'] = $name;

            flash('success', 'Profile updated successfully.');
            redirect(BASE_PATH . '/profile');
        } catch (\Throwable $e) {
            error_log('Profile update error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again.');
            redirect(BASE_PATH . '/profile');
        }
    }
}
