<?php
require_once 'config/database.php';

class AuthController {
    private $conn;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    public function login($data) {
        if (!isset($data['email'], $data['password'])) {
            return json_encode(['status' => 'error', 'message' => 'Missing email or password']);
        }

        $query = "SELECT u.*, u.id as user_id, u.password_hash, u.role_id, r.name as user_type FROM users u JOIN roles r ON u.role_id = r.id WHERE u.email = :email";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':email', $data['email']);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($data['password'], $user['password_hash'])) {
            $payload = [
                'user_id' => $user['user_id'],
                'user_type' => $user['user_type']
            ];

            $token = generateToken($user['user_id'], $user['user_type']);

            $userData = [
                'user_id' => $user['user_id'],
                'user_type' => $user['user_type'],
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name'],
                'email' => $user['email'],
                'phone' => $user['phone'],
                'nin' => $user['nin'],
                'profile_photo' => $user['profile_photo'],
                'role_id' => $user['role_id'],
                'permissions' => isset($user['permissions']) && $user['permissions'] !== null
                    ? json_decode($user['permissions'], true)
                    : null,
            ];

            $query = "UPDATE users SET last_login = NOW() WHERE id = :id";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':id', $user['user_id']);
            $stmt->execute();

            return json_encode([
                'status' => 'success', 
                'message' => 'Login successful', 
                'user' => $userData,
                'token' => $token]);
        } else {
            return json_encode(['status' => 'error', 'message' => 'Invalid credentials']);
        }
    }
}
?>