<?php
namespace App\Controllers;

use Core\View;
use Core\Request;
use Core\Response;
use Core\Validator;
use Core\Auth;
use Core\Session;
use App\Models\User;
use Core\Helpers\EmailHelper;

class AuthController
{
    // ==========================================
    // LOGIN
    // ==========================================
    public function loginPage()
    {
        View::make('auth/login')
            ->setLayout('layout')
            ->with([
                'title' => 'Login - Emergency Response Coordination System',
                'meta_description' => 'Login to your ERCS account to access emergency services or responder dashboards.'
            ])
            ->render();
    }

    public function login()
    {
        $data = Request::all();
        
        $validator = Validator::validate($data)
            ->empty(['email', 'password'])
            ->email(['email']);

        if (!$validator->passes()) {
            return Response::json(['status' => 'error', 'errors' => $validator->errors()], Response::BAD_REQUEST);
        }

        // Attempt to log the user in using Coreflux Auth
        if (Auth::attempt($data['email'], $data['password'])) {
            
            // Retrieve the logged-in user to determine their role and routing
            $user = Auth::user();
            
            $redirectUrl = '/dashboard'; // Default fallback

            if ($user['role'] === 'admin') {
                $redirectUrl = '/admin';
            } elseif ($user['role'] === 'responder') {
                $redirectUrl = '/responder/dashboard';
            }

            return Response::json([
                'status' => 'success', 
                'message' => 'Login successful. Redirecting...',
                'redirect' => $redirectUrl
            ]);
        }

        return Response::json(['status' => 'error', 'message' => 'Invalid email or password.'], Response::UNAUTHORIZED);
    }

    // ==========================================
    // REGISTRATION
    // ==========================================
    public function registerPage()
    {
        View::make('auth/register')
            ->setLayout('layout')
            ->with([
                'title' => 'Create Account - ERCS',
                'meta_description' => 'Register an account to quickly manage and report emergencies.'
            ])
            ->render();
    }

    public function register()
    {
        $data = Request::all();

        $validator = Validator::validate($data)
            ->empty(['full_name', 'email', 'phone_number', 'password'])
            ->email(['email'])
            ->length(['password' => ['min' => 6, 'message' => 'Password must be at least 6 characters.']]);

        if (!$validator->passes()) {
            return Response::json(['status' => 'error', 'errors' => $validator->errors()], Response::BAD_REQUEST);
        }

        // Prevent duplicate emails
        if (User::where('email', $data['email'])) {
            return Response::json(['status' => 'error', 'message' => 'This email is already registered.'], Response::BAD_REQUEST);
        }

        // Handle Phone Number & Account Merging
        $existingPhoneUser = User::where('phone_number', $data['phone_number']);
        
        if ($existingPhoneUser) {
            // Check if the existing account is a temporary guest account (dummy email)
            if (strpos($existingPhoneUser['email'], '@emergency.local') !== false) {
                // MERGE/UPGRADE: Update the guest account with real details
                User::update($existingPhoneUser['id'], [
                    'full_name' => $data['full_name'],
                    'email' => $data['email'],
                    'password' => password_hash($data['password'], PASSWORD_DEFAULT)
                ]);
                
                // Fetch the newly updated user
                $user = User::find($existingPhoneUser['id']);
            } else {
                // It's already a fully registered account, block registration.
                return Response::json(['status' => 'error', 'message' => 'This phone number is already registered to an active account. Please login.'], Response::BAD_REQUEST);
            }
        } else {
            // Create a brand new user in the database
            $user = User::create([
                'full_name' => $data['full_name'],
                'email' => $data['email'],
                'phone_number' => $data['phone_number'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                'role' => 'victim' // Default to standard user. Admin upgrades them to responders later.
            ]);
        }

        if ($user) {
            // Send a welcome email implicitly in the background
            $body = View::renderForEmail('welcome_notification', [
                'name' => $data['full_name']
            ]);
            EmailHelper::queueEmail($data['email'], 'Welcome to ERCS', $body);

            // Log them in immediately
            Auth::attempt($data['email'], $data['password']);

            return Response::json([
                'status' => 'success', 
                'message' => 'Account created successfully!', 
                'redirect' => '/dashboard'
            ]);
        }

        return Response::json(['status' => 'error', 'message' => 'An error occurred while creating your account.'], Response::INTERNAL_SERVER_ERROR);
    }

    // ==========================================
    // LOGOUT
    // ==========================================
    public function logout()
    {
        Auth::logout();
        return Response::redirect('/login');
    }

    // ==========================================
    // PASSWORD RECOVERY (Placeholders)
    // ==========================================
    public function forgotPasswordPage()
    {
        View::make('auth/forgot-password')
            ->setLayout('layout')
            ->with(['title' => 'Recover Password - ERCS'])
            ->render();
    }

    public function sendResetLink()
    {
        $data = Request::all();
        
        $validator = Validator::validate($data)->empty(['email'])->email(['email']);
        
        if (!$validator->passes()) {
            return Response::json(['status' => 'error', 'errors' => $validator->errors()], Response::BAD_REQUEST);
        }

        // In a full production system, generate a token, save to `password_resets` table, and email it.
        // For security, always return success even if the email isn't found (prevents user enumeration).
        return Response::json([
            'status' => 'success', 
            'message' => 'If an account exists with that email, a password reset link has been sent.'
        ]);
    }

    public function resetPasswordPage()
    {
        View::make('auth/reset-password')
            ->setLayout('layout')
            ->with(['title' => 'Reset Password - ERCS'])
            ->render();
    }

    public function resetPassword()
    {
        // Add token validation and update logic here
        return Response::json(['status' => 'success', 'message' => 'Password updated successfully.', 'redirect' => '/login']);
    }
}