<?php
ob_start();
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'POST') {
    $action = $input['action'] ?? '';
    
    switch ($action) {
        case 'login':
            handleLogin($input);
            break;
        case 'logout':
            handleLogout($input);
            break;
        case 'verify':
            verifyToken($input);
            break;
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

function handleLogin($input) {
    $db = getDB();
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    $remember = $input['remember'] ?? false;
    
    if (empty($username) || empty($password)) {
        echo json_encode([
            'success' => false,
            'message' => 'Usuario y contraseña requeridos'
        ]);
        return;
    }
    
    try {
        // Buscar usuario
        $stmt = $db->prepare("
            SELECT u.*, r.name as role_name, r.display_name as role_display
            FROM admin_users u
            JOIN roles r ON u.role_id = r.id
            WHERE u.username = ? AND u.is_active = true
        ");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if (!$user) {
            echo json_encode([
                'success' => false,
                'message' => 'Usuario no encontrado o inactivo'
            ]);
            return;
        }
        
        // Verificar contraseña
        if (!password_verify($password, $user['password_hash'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Contraseña incorrecta'
            ]);
            return;
        }
        
        // Obtener permisos del usuario
        $stmt = $db->prepare("
            SELECT p.name, p.display_name, p.module
            FROM permissions p
            JOIN role_permissions rp ON p.id = rp.permission_id
            WHERE rp.role_id = ?
        ");
        $stmt->execute([$user['role_id']]);
        $permissions = $stmt->fetchAll();
        
        // Generar token
        $token = bin2hex(random_bytes(32));
        $expiresAt = $remember ? 
            date('Y-m-d H:i:s', strtotime('+30 days')) : 
            date('Y-m-d H:i:s', strtotime('+24 hours'));
        
        // Guardar sesión
        $stmt = $db->prepare("
            INSERT INTO admin_sessions (user_id, token, ip_address, user_agent, expires_at)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $user['id'],
            $token,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            $expiresAt
        ]);
        
        // Actualizar último login
        $stmt = $db->prepare("UPDATE admin_users SET last_login = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        // Preparar respuesta
        $userData = [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'full_name' => $user['full_name'],
            'avatar_url' => $user['avatar_url'],
            'role' => [
                'name' => $user['role_name'],
                'display' => $user['role_display']
            ],
            'permissions' => array_map(function($p) {
                return $p['name'];
            }, $permissions),
            'permissions_detail' => $permissions
        ];
        
        echo json_encode([
            'success' => true,
            'token' => $token,
            'user' => $userData,
            'expires_at' => $expiresAt
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor'
        ]);
    }
}

function handleLogout($input) {
    $token = $input['token'] ?? '';
    
    if (empty($token)) {
        echo json_encode([
            'success' => false,
            'message' => 'Token requerido'
        ]);
        return;
    }
    
    $db = getDB();
    $stmt = $db->prepare("DELETE FROM admin_sessions WHERE token = ?");
    $stmt->execute([$token]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Sesión cerrada correctamente'
    ]);
}

function verifyToken($input) {
    $token = $input['token'] ?? '';
    
    if (empty($token)) {
        echo json_encode([
            'success' => false,
            'message' => 'Token requerido'
        ]);
        return;
    }
    
    $db = getDB();
    
    try {
        // Verificar token y obtener usuario
        $stmt = $db->prepare("
            SELECT u.*, r.name as role_name, r.display_name as role_display, s.expires_at
            FROM admin_sessions s
            JOIN admin_users u ON s.user_id = u.id
            JOIN roles r ON u.role_id = r.id
            WHERE s.token = ? AND s.expires_at > CURRENT_TIMESTAMP AND u.is_active = true
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            echo json_encode([
                'success' => false,
                'message' => 'Token inválido o expirado'
            ]);
            return;
        }
        
        // Obtener permisos
        $stmt = $db->prepare("
            SELECT p.name, p.display_name, p.module
            FROM permissions p
            JOIN role_permissions rp ON p.id = rp.permission_id
            WHERE rp.role_id = ?
        ");
        $stmt->execute([$user['role_id']]);
        $permissions = $stmt->fetchAll();
        
        $userData = [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'full_name' => $user['full_name'],
            'avatar_url' => $user['avatar_url'],
            'role' => [
                'name' => $user['role_name'],
                'display' => $user['role_display']
            ],
            'permissions' => array_map(function($p) {
                return $p['name'];
            }, $permissions),
            'permissions_detail' => $permissions
        ];
        
        echo json_encode([
            'success' => true,
            'user' => $userData,
            'expires_at' => $user['expires_at']
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error del servidor'
        ]);
    }
}
