<?php
// backend/api/controllers/AuthController.php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../utils/helpers.php';
require_once __DIR__ . '/../../utils/email-templates.php';
require_once __DIR__ . '/../../utils/mailer.php';

class AuthController {
    
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function login($input) {
        validateInput($input, ['email', 'password']);
            
        $email = $input['email'];
        $password = $input['password'];
        
        // Find user
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if (!$user) {
            errorResponse('Invalid email or password', 401);
        }
        
        // Verify password
        if (!password_verify($password, $user['password_hash'])) {
            errorResponse('Invalid email or password', 401);
        }

        // Admins bypass verification and approval checks
        if (!isAdmin($user['id'])) {
            if (isset($user['email_verified']) && $user['email_verified'] == 0) {
                errorResponse('Please verify your email address before logging in.', 403);
            }

            if (isset($user['is_approved']) && $user['is_approved'] == 0) {
                errorResponse('Your account is pending administrator approval.', 403);
            }
        }
        
        // Update last login
        $stmt = $this->pdo->prepare("UPDATE users SET last_login = datetime('now') WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        // Create session
        $sessionToken = createSession($user['id']);
        
        // Fetch profile role info
        $stmt = $this->pdo->prepare("SELECT r.name as role FROM profiles p JOIN user_roles r ON p.role_id = r.id WHERE p.user_id = ?");
        $stmt->execute([$user['id']]);
        $profile = $stmt->fetch();

        return [
            'user' => [
                'id' => $user['id'],
                'email' => $user['email'],
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name']
            ],
            'profile' => $profile,
            'session_token' => $sessionToken
        ];
    }

    public function register($input) {
        validateInput($input, ['email', 'password']);
            
        $email = $input['email'];
        $password = $input['password'];
        $firstName = isset($input['firstName']) ? $input['firstName'] : null;
        $lastName = isset($input['lastName']) ? $input['lastName'] : null;
        
        // Check if user already exists
        $stmt = $this->pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            errorResponse('User with this email already exists', 400);
        }
        
        // Create user
        $userId = generateUUID();
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $verificationToken = bin2hex(random_bytes(32));
        
        // Insert with is_approved=0, email_verified=0
        $stmt = $this->pdo->prepare("INSERT INTO users (id, email, password_hash, first_name, last_name, is_approved, email_verified, verification_token) VALUES (?, ?, ?, ?, ?, 0, 0, ?)");
        $stmt->execute([$userId, $email, $passwordHash, $firstName, $lastName, $verificationToken]);
        
        // Create profile
        $profileId = generateUUID();
        $stmt = $this->pdo->prepare("INSERT INTO profiles (id, user_id, first_name, last_name, role_id) VALUES (?, ?, ?, ?, 2)"); // 2 = user role
        $stmt->execute([$profileId, $userId, $firstName, $lastName]);
        
        // Create user progress
        $progressId = generateUUID();
        $stmt = $this->pdo->prepare("INSERT INTO user_progress (id, user_id) VALUES (?, ?)");
        $stmt->execute([$progressId, $userId]);
        
        // Create user profile
        $userProfileId = generateUUID();
        $baseUsername = $firstName ? strtolower(str_replace(' ', '', $firstName)) : explode('@', $email)[0];
        $username = $baseUsername;
        
        // Ensure username uniqueness
        $stmt = $this->pdo->prepare("SELECT id FROM user_profiles WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            $username = $baseUsername . '_' . bin2hex(random_bytes(2));
        }
        
        $stmt = $this->pdo->prepare("INSERT INTO user_profiles (id, user_id, first_name, last_name, username) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$userProfileId, $userId, $firstName, $lastName, $username]);
        
        // Generate Verification Link
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $verificationLink = "$protocol://$host/backend/api/verify-email.php?token=$verificationToken";

        // Send Verification Email
        $subject = "Verify Your Email Address";
        $content = "
            <h2>Welcome to FlashCORE!</h2>
            <p>Thank you for registering. Please click the button below to verify your email address and activate your account.</p>
            <div style='text-align: center; margin: 30px 0;'>
                <a href='$verificationLink' class='button'>Verify Email Address</a>
            </div>
            <p style='font-size: 12px; color: #71717a;'>If the button doesn't work, copy and paste this link into your browser:</p>
            <p style='font-size: 12px; color: #71717a; word-break: break-all;'>$verificationLink</p>
        ";
        
        $htmlBody = getBrandedTemplate($content, $subject);
        sendRobustEmail($email, $subject, $htmlBody);

        return [
            'message' => 'Registration successful. Please check your email to verify your account.',
            'require_verification' => true
        ];
    }

    public function logout() {
        // In a real implementation, you would invalidate the session token
        return ['message' => 'Logged out successfully'];
    }
}
?>
