<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Cart AJAX Handlers - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/pos/sales/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

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

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}

// Require authentication
require_auth();

// Define helper functions if they don't exist
if (!function_exists('is_ajax_request')) {
    function is_ajax_request() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('json_success')) {
    function json_success($data = null, $message = 'Success') {
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'success',
            'message' => $message,
            'data' => $data
        ]);
        exit;
    }
}

if (!function_exists('json_error')) {
    function json_error($message = 'Error', $errors = null, $status_code = 400) {
        http_response_code($status_code);
        header('Content-Type: application/json');
        $response = [
            'status' => 'error',
            'message' => $message
        ];
        if ($errors !== null) {
            $response['errors'] = $errors;
        }
        echo json_encode($response);
        exit;
    }
}

// Check if it's an AJAX request
if (!is_ajax_request() && !isset($_GET['test'])) {
    http_response_code(403);
    exit('Direct access not permitted');
}

// Get action
$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'get_products':
        get_products();
        break;
        
    case 'search_products':
        search_products();
        break;
        
    case 'get_product_details':
        get_product_details();
        break;
        
    case 'validate_stock':
        validate_stock();
        break;
        
    case 'test':
        echo "AJAX endpoint is working. Available actions: get_products, search_products, get_product_details, validate_stock";
        break;
        
    default:
        if (isset($_GET['test'])) {
            echo "AJAX endpoint is working. Action parameter is required.";
        } else {
            json_error('Invalid action');
        }
}

/**
 * Get products by category
 */
function get_products() {
    $category_id = isset($_GET['category']) && $_GET['category'] !== 'all' ? (int)$_GET['category'] : null;
    
    try {
        $sql = "
            SELECT p.*, c.category_name
            FROM pos_products p
            LEFT JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.is_active = 1
        ";
        
        $params = [];
        
        if ($category_id) {
            $sql .= " AND p.category_id = ?";
            $params[] = $category_id;
        }
        
        $sql .= " ORDER BY c.sort_order, p.product_name LIMIT 100";
        
        $products = db_fetch_all($sql, $params) ?: [];
        
        if (empty($products)) {
            echo '<div class="text-center text-muted py-5">No products found in this category</div>';
            return;
        }
        
        foreach ($products as $product) {
            $stock_class = '';
            $stock_badge = '';
            $disabled_attr = '';
            $disabled_style = '';
            
            if (!empty($product['stock_item'])) {
                if (($product['current_stock'] ?? 0) <= 0) {
                    $stock_class = 'out-of-stock';
                    $stock_badge = '<span class="badge bg-danger">Out of Stock</span>';
                    $disabled_attr = ' disabled';
                    $disabled_style = 'style="opacity: 0.5; pointer-events: none;"';
                } elseif (($product['current_stock'] ?? 0) <= ($product['min_stock'] ?? 0)) {
                    $stock_class = 'low-stock';
                    $stock_badge = '<span class="badge bg-warning">Low Stock</span>';
                }
            }
            ?>
            <div class="pos-product-item <?php echo $stock_class; ?>" 
                 onclick="<?php echo empty($disabled_attr) ? "addToCart(" . ($product['product_id'] ?? 0) . ", '" . addslashes($product['product_name'] ?? 'Product') . "', " . ($product['unit_price'] ?? 0) . ")" : ''; ?>"
                 <?php echo $disabled_style; ?>>
                <div class="product-name"><?php echo escape_html($product['product_name'] ?? 'Product'); ?></div>
                <div class="price"><?php echo format_currency($product['unit_price'] ?? 0); ?></div>
                <?php if (!empty($stock_badge)): ?>
                    <div class="stock-badge"><?php echo $stock_badge; ?></div>
                <?php endif; ?>
                <?php if (!empty($product['product_code'])): ?>
                    <div class="product-code small text-muted"><?php echo escape_html($product['product_code']); ?></div>
                <?php endif; ?>
            </div>
            <?php
        }
        
    } catch (Exception $e) {
        error_log("Error in get_products: " . $e->getMessage());
        echo '<div class="text-center text-muted py-5">Error loading products</div>';
    }
}

/**
 * Search products
 */
function search_products() {
    $query = $_GET['query'] ?? '';
    
    if (empty($query) || strlen($query) < 2) {
        echo '<div class="text-center text-muted py-5">Type at least 2 characters to search</div>';
        return;
    }
    
    try {
        $search_term = "%$query%";
        
        $products = db_fetch_all("
            SELECT p.*, c.category_name
            FROM pos_products p
            LEFT JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.is_active = 1
            AND (p.product_name LIKE ? OR p.product_code LIKE ? OR p.barcode LIKE ?)
            ORDER BY 
                CASE 
                    WHEN p.product_name LIKE ? THEN 1
                    WHEN p.product_code LIKE ? THEN 2
                    ELSE 3
                END,
                p.product_name
            LIMIT 50
        ", [$search_term, $search_term, $search_term, $query . '%', $query . '%']) ?: [];
        
        if (empty($products)) {
            echo '<div class="text-center text-muted py-5">No products found matching "' . escape_html($query) . '"</div>';
            return;
        }
        
        foreach ($products as $product) {
            $stock_class = '';
            $stock_badge = '';
            $disabled_attr = '';
            $disabled_style = '';
            
            if (!empty($product['stock_item'])) {
                if (($product['current_stock'] ?? 0) <= 0) {
                    $stock_class = 'out-of-stock';
                    $stock_badge = '<span class="badge bg-danger">Out of Stock</span>';
                    $disabled_attr = ' disabled';
                    $disabled_style = 'style="opacity: 0.5; pointer-events: none;"';
                } elseif (($product['current_stock'] ?? 0) <= ($product['min_stock'] ?? 0)) {
                    $stock_class = 'low-stock';
                    $stock_badge = '<span class="badge bg-warning">Low Stock</span>';
                }
            }
            ?>
            <div class="pos-product-item <?php echo $stock_class; ?>" 
                 onclick="<?php echo empty($disabled_attr) ? "addToCart(" . ($product['product_id'] ?? 0) . ", '" . addslashes($product['product_name'] ?? 'Product') . "', " . ($product['unit_price'] ?? 0) . ")" : ''; ?>"
                 <?php echo $disabled_style; ?>>
                <div class="product-name"><?php echo escape_html($product['product_name'] ?? 'Product'); ?></div>
                <div class="price"><?php echo format_currency($product['unit_price'] ?? 0); ?></div>
                <?php if (!empty($stock_badge)): ?>
                    <div class="stock-badge"><?php echo $stock_badge; ?></div>
                <?php endif; ?>
                <div class="product-code small text-muted"><?php echo escape_html($product['product_code'] ?? ''); ?></div>
            </div>
            <?php
        }
        
    } catch (Exception $e) {
        error_log("Error in search_products: " . $e->getMessage());
        echo '<div class="text-center text-muted py-5">Error searching products</div>';
    }
}

/**
 * Get product details
 */
function get_product_details() {
    $product_id = (int)($_GET['product_id'] ?? 0);
    
    if (!$product_id) {
        json_error('Invalid product ID');
    }
    
    try {
        $product = db_fetch_one("
            SELECT p.*, c.category_name
            FROM pos_products p
            LEFT JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.product_id = ?
        ", [$product_id]);
        
        if (!$product) {
            json_error('Product not found');
        }
        
        // Check stock availability
        if (!empty($product['stock_item']) && ($product['current_stock'] ?? 0) <= 0) {
            json_error('Product is out of stock');
        }
        
        json_success($product);
        
    } catch (Exception $e) {
        error_log("Error in get_product_details: " . $e->getMessage());
        json_error('Database error: ' . $e->getMessage());
    }
}

/**
 * Validate stock for multiple products
 */
function validate_stock() {
    $items = json_decode($_POST['items'] ?? '[]', true);
    
    if (empty($items)) {
        json_success(['valid' => true]);
    }
    
    $errors = [];
    
    try {
        foreach ($items as $item) {
            $product = db_fetch_one("
                SELECT current_stock, stock_item, min_stock 
                FROM pos_products 
                WHERE product_id = ?
            ", [$item['id']]);
            
            if (!$product) {
                $errors[] = "Product ID {$item['id']} not found";
                continue;
            }
            
            if (!empty($product['stock_item']) && ($product['current_stock'] ?? 0) < ($item['quantity'] ?? 0)) {
                $product_name = $item['name'] ?? "Product {$item['id']}";
                $errors[] = "Insufficient stock for {$product_name}. Available: {$product['current_stock']}, Requested: {$item['quantity']}";
            }
        }
        
        if (empty($errors)) {
            json_success(['valid' => true]);
        } else {
            json_error('Stock validation failed', ['errors' => $errors]);
        }
        
    } catch (Exception $e) {
        error_log("Error in validate_stock: " . $e->getMessage());
        json_error('Database error: ' . $e->getMessage());
    }
}
?>