<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Search API - Enhanced Version
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path to root
$base_path = dirname(__DIR__, 2); // Goes up two levels from /api/ to root

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Require authentication for API access
require_auth();

// Set content type to JSON
header('Content-Type: application/json');

// Get search parameters
$query = isset($_GET['q']) ? trim($_GET['q']) : (isset($_GET['query']) ? trim($_GET['query']) : '');
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Validate input
if (empty($query)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Search query is required',
        'data' => []
    ]);
    exit;
}

if (strlen($query) < 2) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Search query must be at least 2 characters',
        'data' => []
    ]);
    exit;
}

try {
    // Search in guests table with multiple fields
    $search_term = "%$query%";
    
    // Count total results for pagination
    $count_sql = "SELECT COUNT(*) as total FROM guests 
                  WHERE first_name LIKE ? 
                  OR last_name LIKE ? 
                  OR CONCAT(first_name, ' ', last_name) LIKE ?
                  OR email LIKE ? 
                  OR phone LIKE ? 
                  OR guest_code LIKE ?
                  OR id_number LIKE ?";
    
    $count_params = [$search_term, $search_term, $search_term, $search_term, $search_term, $search_term, $search_term];
    
    $count_result = db_fetch_one($count_sql, $count_params);
    $total_results = $count_result['total'] ?? 0;
    
    // Get paginated results
    $sql = "SELECT 
                guest_id,
                guest_code,
                first_name,
                last_name,
                email,
                phone,
                id_type,
                id_number,
                nationality,
                is_blacklisted,
                blacklist_reason,
                created_at,
                (SELECT COUNT(*) FROM reservations WHERE guest_id = guests.guest_id) as total_stays,
                (SELECT MAX(check_in_date) FROM reservations WHERE guest_id = guests.guest_id) as last_stay
            FROM guests 
            WHERE first_name LIKE ? 
            OR last_name LIKE ? 
            OR CONCAT(first_name, ' ', last_name) LIKE ?
            OR email LIKE ? 
            OR phone LIKE ? 
            OR guest_code LIKE ?
            OR id_number LIKE ?
            ORDER BY 
                CASE 
                    WHEN guest_code LIKE ? THEN 1
                    WHEN phone LIKE ? THEN 2
                    WHEN email LIKE ? THEN 3
                    WHEN first_name LIKE ? OR last_name LIKE ? THEN 4
                    ELSE 5
                END,
                first_name ASC,
                last_name ASC
            LIMIT ? OFFSET ?";
    
    $params = [
        $search_term, $search_term, $search_term, $search_term, 
        $search_term, $search_term, $search_term,
        $query . '%', $query . '%', $query . '%', $query . '%', $query . '%',
        $limit, $offset
    ];
    
    $guests = db_fetch_all($sql, $params);
    
    if ($guests === false) {
        throw new Exception('Database query failed');
    }
    
    // Format the results
    $formatted_guests = [];
    foreach ($guests as $guest) {
        // Determine best display name
        $display_name = trim($guest['first_name'] . ' ' . $guest['last_name']);
        if (empty($display_name)) {
            $display_name = $guest['guest_code'] ?? 'Unknown';
        }
        
        // Format last stay date
        $last_stay_formatted = null;
        if (!empty($guest['last_stay'])) {
            $last_stay_formatted = date('M d, Y', strtotime($guest['last_stay']));
        }
        
        $formatted_guests[] = [
            'guest_id' => (int)$guest['guest_id'],
            'guest_code' => $guest['guest_code'],
            'first_name' => $guest['first_name'],
            'last_name' => $guest['last_name'],
            'full_name' => $display_name,
            'email' => $guest['email'],
            'phone' => $guest['phone'],
            'id_type' => $guest['id_type'],
            'id_number' => $guest['id_number'],
            'nationality' => $guest['nationality'],
            'is_blacklisted' => (bool)$guest['is_blacklisted'],
            'blacklist_reason' => $guest['blacklist_reason'],
            'total_stays' => (int)$guest['total_stays'],
            'last_stay' => $guest['last_stay'],
            'last_stay_formatted' => $last_stay_formatted,
            'created_at' => $guest['created_at'],
            'created_at_formatted' => date('M d, Y', strtotime($guest['created_at']))
        ];
    }
    
    // Return success response with pagination info
    echo json_encode([
        'status' => 'success',
        'message' => 'Search completed successfully',
        'data' => $formatted_guests,
        'pagination' => [
            'total' => (int)$total_results,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total_results / $limit),
            'has_more' => ($page * $limit) < $total_results
        ],
        'query' => $query
    ]);
    
} catch (Exception $e) {
    // Log error
    error_log("Guest search API error: " . $e->getMessage());
    
    // Return error response
    echo json_encode([
        'status' => 'error',
        'message' => 'An error occurred while searching',
        'error_details' => $e->getMessage(),
        'data' => []
    ]);
}
?>