<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class AuthController extends Controller {
    
    public function showLogin() {
        // If already logged in, redirect to dashboard
        if (isset($_SESSION['user_id'])) {
            header('Location: ' . APP_URL . '/dashboard');
            exit;
        }
        
        // Render login view directly without layout
        $this->renderLogin([
            'title' => 'Login',
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    private function renderLogin($data = []) {
        extract($data);
        include APP_PATH . '/views/auth/login.php';
    }
    
    public function login() {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }
    
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = 'Please enter username and password';
        $this->renderLogin([
            'title' => 'Login',
            'error' => $error,
            'csrf_token' => $this->csrf_token()
        ]);
        return;
    }
    
    $userModel = new User();
    $user = $userModel->authenticate($username, $password);
    
    if ($user) {
        // Set ALL session variables - both role keys for compatibility
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['role'] = $user['role'];        // For some parts of the app
        $_SESSION['user_role'] = $user['role'];   // For UserController and other parts
        
        // Debug log
        error_log("User logged in: ID=" . $user['id'] . ", Role=" . $user['role']);
        
        $userModel->updateLastLogin($user['id'], $_SERVER['REMOTE_ADDR']);
        
        header('Location: ' . APP_URL . '/dashboard');
        exit;
    } else {
        $error = 'Invalid username or password';
        $this->renderLogin([
            'title' => 'Login',
            'error' => $error,
            'csrf_token' => $this->csrf_token()
        ]);
    }
}
    
    public function logout() {
        session_destroy();
        header('Location: ' . APP_URL . '/');
        exit;
    }
    
    /**
     * Change password - AJAX endpoint
     */
    public function changePassword() {
        $this->requireAuth();
        
        // Verify CSRF
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            $this->json(['error' => 'Invalid CSRF token'], 400);
            return;
        }
        
        $current = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';
        
        // Validate
        if (empty($current) || empty($new) || empty($confirm)) {
            $this->json(['error' => 'All fields are required'], 400);
            return;
        }
        
        if ($new !== $confirm) {
            $this->json(['error' => 'New passwords do not match'], 400);
            return;
        }
        
        if (strlen($new) < 8) {
            $this->json(['error' => 'Password must be at least 8 characters'], 400);
            return;
        }
        
        $userModel = new \App\Models\User();
        $user = $userModel->find($_SESSION['user_id']);
        
        if (!$user) {
            $this->json(['error' => 'User not found'], 404);
            return;
        }
        
        if (!\Security::verifyPassword($current, $user['password_hash'])) {
            $this->json(['error' => 'Current password is incorrect'], 400);
            return;
        }
        
        $updated = $userModel->update($user['id'], [
            'password_hash' => \Security::hashPassword($new)
        ]);
        
        if ($updated) {
            $this->json(['success' => true, 'message' => 'Password changed successfully']);
        } else {
            $this->json(['error' => 'Failed to change password'], 500);
        }
    }
    
    /**
     * Helper method for JSON responses
     */
    protected function json($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}