<?php
/**
 * User Authentication Controller
 * Handles registration, login, logout, password reset
 */

namespace App\Controller;

class AuthController {
    protected $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    /**
     * Register new user
     */
    public function register($data) {
        try {
            // Validate required fields
            if (empty($data['username']) || empty($data['email']) || empty($data['password']) || empty($data['full_name'])) {
                return ['success' => false, 'error' => 'Missing required fields'];
            }
            
            // Validate email format
            if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                return ['success' => false, 'error' => 'Invalid email format'];
            }
            
            // Check if username already exists
            $stmt = $this->db->prepare('SELECT id FROM users WHERE username = ?');
            $stmt->execute([$data['username']]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Username already exists'];
            }
            
            // Check if email already exists
            $stmt = $this->db->prepare('SELECT id FROM users WHERE email = ?');
            $stmt->execute([$data['email']]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Email already registered'];
            }
            
            // Hash password
            $hashedPassword = password_hash($data['password'], PASSWORD_BCRYPT);
            
            // Generate API key
            $apiKey = bin2hex(random_bytes(32));
            
            // Insert new user (auto-approved)
            $stmt = $this->db->prepare('
                INSERT INTO users (username, email, password, full_name, status, account_type, api_key, primary_currency, created_at)
                VALUES (?, ?, ?, ?, "active", "user", ?, ?, NOW())
            ');
            
            $result = $stmt->execute([
                $data['username'],
                $data['email'],
                $hashedPassword,
                $data['full_name'],
                $apiKey,
                'UGX'
            ]);
            
            if (!$result) {
                return ['success' => false, 'error' => 'Registration failed'];
            }
            
            $userId = $this->db->lastInsertId();
            
            // Log initial transaction (account created, 0 balance)
            $logStmt = $this->db->prepare('
                INSERT INTO transactions (user_id, transaction_type, description, amount, previous_balance, new_balance, status)
                VALUES (?, "charge", "Account created", 0, 0, 0, "completed")
            ');
            $logStmt->execute([$userId]);
            
            return [
                'success' => true,
                'message' => 'Registration successful! You can now login.',
                'user_id' => $userId,
                'api_key' => $apiKey
            ];
            
        } catch (\Exception $e) {
            error_log('Registration Error: ' . $e->getMessage());
            return ['success' => false, 'error' => 'Registration failed: ' . $e->getMessage()];
        }
    }
    
    /**
     * User login
     */
    public function login($username, $password) {
        try {
            // Get user by username or email
            $stmt = $this->db->prepare('
                SELECT id, username, email, password, status, account_type, full_name, balance, primary_currency
                FROM users
                WHERE (username = ? OR email = ?) AND status != "banned"
            ');
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);
            
            if (!$user) {
                return ['success' => false, 'error' => 'Invalid credentials'];
            }
            
            // Verify password
            if (!password_verify($password, $user['password'])) {
                return ['success' => false, 'error' => 'Invalid credentials'];
            }
            
            // Check if account is active
            if ($user['status'] !== 'active') {
                return ['success' => false, 'error' => 'Account is ' . $user['status']];
            }
            
            // Update last login
            $updateStmt = $this->db->prepare('UPDATE users SET last_login = NOW() WHERE id = ?');
            $updateStmt->execute([$user['id']]);
            
            // Create session
            session_start();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['user_type'] = $user['account_type'];
            $_SESSION['balance'] = $user['balance'];
            $_SESSION['currency'] = $user['primary_currency'];
            $_SESSION['login_time'] = time();
            
            // Remove password from return data
            unset($user['password']);
            
            return [
                'success' => true,
                'message' => 'Login successful',
                'user' => $user
            ];
            
        } catch (\Exception $e) {
            error_log('Login Error: ' . $e->getMessage());
            return ['success' => false, 'error' => 'Login failed'];
        }
    }
    
    /**
     * User logout
     */
    public function logout() {
        session_start();
        session_destroy();
        return ['success' => true, 'message' => 'Logged out successfully'];
    }
    
    /**
     * Check if user is logged in
     */
    public function isLoggedIn() {
        session_start();
        return isset($_SESSION['user_id']);
    }
    
    /**
     * Get current user
     */
    public function getCurrentUser() {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            return null;
        }
        
        $stmt = $this->db->prepare('
            SELECT id, username, email, full_name, balance, primary_currency, status, account_type
            FROM users
            WHERE id = ?
        ');
        $stmt->execute([$_SESSION['user_id']]);
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Update user profile
     */
    public function updateProfile($userId, $data) {
        try {
            $updates = [];
            $values = [];
            $allowedFields = ['full_name', 'phone', 'country', 'primary_currency'];
            
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updates[] = "$field = ?";
                    $values[] = $data[$field];
                }
            }
            
            if (empty($updates)) {
                return ['success' => false, 'error' => 'No valid fields to update'];
            }
            
            $values[] = $userId;
            $sql = 'UPDATE users SET ' . implode(', ', $updates) . ' WHERE id = ?';
            $stmt = $this->db->prepare($sql);
            $stmt->execute($values);
            
            return ['success' => true, 'message' => 'Profile updated successfully'];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Change password
     */
    public function changePassword($userId, $oldPassword, $newPassword) {
        try {
            // Get current password
            $stmt = $this->db->prepare('SELECT password FROM users WHERE id = ?');
            $stmt->execute([$userId]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);
            
            if (!$user) {
                return ['success' => false, 'error' => 'User not found'];
            }
            
            // Verify old password
            if (!password_verify($oldPassword, $user['password'])) {
                return ['success' => false, 'error' => 'Current password is incorrect'];
            }
            
            // Hash new password
            $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
            
            // Update password
            $updateStmt = $this->db->prepare('UPDATE users SET password = ? WHERE id = ?');
            $updateStmt->execute([$hashedPassword, $userId]);
            
            return ['success' => true, 'message' => 'Password changed successfully'];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Reset API key
     */
    public function resetApiKey($userId) {
        try {
            $newApiKey = bin2hex(random_bytes(32));
            $stmt = $this->db->prepare('UPDATE users SET api_key = ? WHERE id = ?');
            $stmt->execute([$newApiKey, $userId]);
            
            return ['success' => true, 'api_key' => $newApiKey];
            
        } catch (\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}
?>
