<?php

namespace App\Controllers;

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

class SettingsController {
    public function profile() {
        if (!Auth::check() || Auth::user()['role'] === 'student') {
            redirect('/login');
            exit;
        }

        $user = Auth::user();
        $title = 'My Profile';
        require_once __DIR__ . '/../../views/admin/profile.php';
    }

    public function updateProfile() {
        if (!Auth::check() || Auth::user()['role'] === 'student') {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $db = \App\Core\Database::getInstance();
            $userId = Auth::user()['id'];
            
            $email = $_POST['email'] ?? '';
            $currentPassword = $_POST['current_password'] ?? '';
            $newPassword = $_POST['new_password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';

            if (empty($email)) {
                $_SESSION['toast'] = ['message' => 'Email is required.', 'type' => 'error'];
                redirect('/admin/profile');
                exit;
            }

            // If changing password, verify current password first
            if (!empty($newPassword) || !empty($currentPassword)) {
                if (empty($currentPassword)) {
                    $_SESSION['toast'] = ['message' => 'Current password is required to make changes.', 'type' => 'error'];
                    redirect('/admin/profile');
                    exit;
                }

                $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $userRecord = $stmt->fetch();

                if (!$userRecord || !password_verify($currentPassword, $userRecord['password'])) {
                    $_SESSION['toast'] = ['message' => 'Incorrect current password.', 'type' => 'error'];
                    redirect('/admin/profile');
                    exit;
                }

                if (!empty($newPassword)) {
                    if ($newPassword !== $confirmPassword) {
                        $_SESSION['toast'] = ['message' => 'New passwords do not match.', 'type' => 'error'];
                        redirect('/admin/profile');
                        exit;
                    }
                    if (strlen($newPassword) < 6) {
                        $_SESSION['toast'] = ['message' => 'New password must be at least 6 characters.', 'type' => 'error'];
                        redirect('/admin/profile');
                        exit;
                    }

                    // Update email and password
                    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("UPDATE users SET email = ?, password = ? WHERE id = ?");
                    $stmt->execute([$email, $hashedPassword, $userId]);
                    $_SESSION['toast'] = ['message' => 'Profile and password updated successfully.', 'type' => 'success'];
                } else {
                    // Update email only
                    $stmt = $db->prepare("UPDATE users SET email = ? WHERE id = ?");
                    $stmt->execute([$email, $userId]);
                    $_SESSION['toast'] = ['message' => 'Profile updated successfully.', 'type' => 'success'];
                }
            } else {
                // Update email only (no password fields filled)
                $stmt = $db->prepare("UPDATE users SET email = ? WHERE id = ?");
                $stmt->execute([$email, $userId]);
                $_SESSION['toast'] = ['message' => 'Profile updated successfully.', 'type' => 'success'];
            }

            // Update session data
            $_SESSION['user_email'] = $email;
        }

        redirect('/admin/profile');
    }

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

        $settingModel = new Setting();
        $settings = $settingModel->getAll();
        $title = 'Institute Settings';
        
        require_once __DIR__ . '/../../views/admin/settings.php';
    }

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $settingModel = new Setting();
            
            $fields = [
                'institute_name', 'institute_email', 'institute_phone', 
                'institute_address', 
            ];

            foreach ($fields as $field) {
                if (isset($_POST[$field])) {
                    $settingModel->update($field, $_POST[$field]);
                }
            }

            $uploadDir = __DIR__ . '/../../public/uploads/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

            if (isset($_FILES['institute_logo']) && $_FILES['institute_logo']['error'] === UPLOAD_ERR_OK) {
                $fileName = 'logo_' . time() . '_' . basename($_FILES['institute_logo']['name']);
                if (move_uploaded_file($_FILES['institute_logo']['tmp_name'], $uploadDir . $fileName)) {
                    $settingModel->update('institute_logo', '/uploads/' . $fileName);
                }
            }

            if (isset($_FILES['institute_favicon']) && $_FILES['institute_favicon']['error'] === UPLOAD_ERR_OK) {
                $fileName = 'favicon_' . time() . '_' . basename($_FILES['institute_favicon']['name']);
                if (move_uploaded_file($_FILES['institute_favicon']['tmp_name'], $uploadDir . $fileName)) {
                    $settingModel->update('institute_favicon', '/uploads/' . $fileName);
                }
            }

            $_SESSION['toast'] = ['message' => 'Settings updated successfully!', 'type' => 'success'];
            redirect('/admin/settings');
            exit;
        }
    }
}
