<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Authentication API
 * Developer: JOACHIM'S INNOTECH
 */

// This file is included from index.php, so we don't need to re-initialize everything

// Handle different actions based on method and subresource
$action = $id ?? '';

switch ($method) {
    case 'POST':
        if ($action === 'login') {
            handle_login();
        } elseif ($action === 'logout') {
            handle_logout();
        } elseif ($action === 'refresh') {
            handle_token_refresh();
        } else {
            json_response(['error' => 'Invalid action'], 400);
        }
        break;
        
    case 'GET':
        if ($action === 'me') {
            handle_get_current_user();
        } elseif ($action === 'verify') {
            handle_verify_token();
        } else {
            json_response(['error' => 'Invalid action'], 400);
        }
        break;
        
    default:
        json_response(['error' => 'Method not allowed'], 405);
}

/**
 * Handle login request
 */
function handle_login() {
    // Get POST data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        $input = $_POST;
    }
    
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    $remember = isset($input['remember']) ? (bool)$input['remember'] : false;
    
    if (empty($username) || empty($password)) {
        json_response(['error' => 'Username and password are required'], 400);
    }
    
    // Authenticate user
    $result = authenticate_user($username, $password, $remember);
    
    if (is_array($result) && isset($result['error'])) {
        $error_messages = [
            'too_many_attempts' => 'Too many login attempts. Please try again later.',
            'invalid_credentials' => 'Invalid username or password'
        ];
        
        $message = $error_messages[$result['error']] ?? 'Authentication failed';
        json_response(['error' => $message], 401);
    }
    
    // Generate API token
    $token = generate_api_token($result['user_id']);
    
    // Get user data without sensitive info
    $user = [
        'user_id' => $result['user_id'],
        'username' => $result['username'],
        'email' => $result['email'],
        'first_name' => $result['first_name'],
        'last_name' => $result['last_name'],
        'role_id' => $result['role_id']
    ];
    
    json_response([
        'success' => true,
        'message' => 'Login successful',
        'token' => $token,
        'user' => $user
    ]);
}

/**
 * Handle logout request
 */
function handle_logout() {
    // Verify token
    $user_id = verify_api_request();
    
    if (!$user_id) {
        json_response(['error' => 'Invalid or expired token'], 401);
    }
    
    // Invalidate token
    invalidate_api_token(get_bearer_token());
    
    // Logout user from session
    logout_user();
    
    json_response([
        'success' => true,
        'message' => 'Logout successful'
    ]);
}

/**
 * Handle get current user
 */
function handle_get_current_user() {
    // Verify token
    $user_id = verify_api_request();
    
    if (!$user_id) {
        json_response(['error' => 'Invalid or expired token'], 401);
    }
    
    // Get user data
    $user = db_fetch_one("
        SELECT user_id, username, email, first_name, last_name, role_id, department 
        FROM users WHERE user_id = ?
    ", [$user_id]);
    
    if (!$user) {
        json_response(['error' => 'User not found'], 404);
    }
    
    // Get permissions
    $permissions = get_user_permissions($user_id);
    $user['permissions'] = array_column($permissions, 'permission_key');
    
    json_response([
        'success' => true,
        'user' => $user
    ]);
}

/**
 * Handle token refresh
 */
function handle_token_refresh() {
    $old_token = get_bearer_token();
    
    if (!$old_token) {
        json_response(['error' => 'No token provided'], 401);
    }
    
    // Verify old token
    $user_id = verify_api_token($old_token);
    
    if (!$user_id) {
        json_response(['error' => 'Invalid token'], 401);
    }
    
    // Invalidate old token
    invalidate_api_token($old_token);
    
    // Generate new token
    $new_token = generate_api_token($user_id);
    
    json_response([
        'success' => true,
        'token' => $new_token
    ]);
}

/**
 * Handle verify token
 */
function handle_verify_token() {
    $token = $_GET['token'] ?? get_bearer_token();
    
    if (!$token) {
        json_response(['error' => 'No token provided'], 401);
    }
    
    $user_id = verify_api_token($token);
    
    if (!$user_id) {
        json_response(['error' => 'Invalid token'], 401);
    }
    
    json_response([
        'success' => true,
        'message' => 'Token is valid',
        'user_id' => $user_id
    ]);
}

/**
 * Generate API token
 */
function generate_api_token($user_id) {
    $token = bin2hex(random_bytes(32));
    $expires = date(DATETIME_FORMAT, time() + 86400); // 24 hours
    
    // Store token in database (create api_tokens table if not exists)
    create_api_tokens_table();
    
    db_insert('api_tokens', [
        'user_id' => $user_id,
        'token' => hash('sha256', $token),
        'expires_at' => $expires,
        'created_at' => date(DATETIME_FORMAT)
    ]);
    
    return $token;
}

/**
 * Verify API token
 */
function verify_api_token($token) {
    $hashed = hash('sha256', $token);
    
    $record = db_fetch_one("
        SELECT user_id, expires_at FROM api_tokens 
        WHERE token = ? AND expires_at > NOW()
    ", [$hashed]);
    
    return $record ? $record['user_id'] : false;
}

/**
 * Invalidate API token
 */
function invalidate_api_token($token) {
    $hashed = hash('sha256', $token);
    db_delete('api_tokens', 'token = ?', [$hashed]);
}

/**
 * Get bearer token from request headers
 */
function get_bearer_token() {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (preg_match('/Bearer\s+(.*)$/i', $auth_header, $matches)) {
        return $matches[1];
    }
    
    return null;
}

/**
 * Verify API request and return user ID
 */
function verify_api_request() {
    $token = get_bearer_token();
    
    if (!$token) {
        return false;
    }
    
    return verify_api_token($token);
}

/**
 * Create API tokens table if not exists
 */
function create_api_tokens_table() {
    $pdo = get_db_connection();
    
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS api_tokens (
            token_id INT PRIMARY KEY AUTO_INCREMENT,
            user_id INT NOT NULL,
            token VARCHAR(64) NOT NULL UNIQUE,
            expires_at DATETIME NOT NULL,
            created_at DATETIME NOT NULL,
            INDEX idx_token (token),
            INDEX idx_expires (expires_at),
            FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    // Clean up expired tokens
    $pdo->exec("DELETE FROM api_tokens WHERE expires_at < NOW()");
}

// Create table if it doesn't exist
create_api_tokens_table();