<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Purchase Order - FIXED PATH
 * 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 from admin/inventory/purchases/
$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/admin/inventory/purchases/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// 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';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define csrf_token function if it doesn't exist
if (!function_exists('csrf_token')) {
    function csrf_token() {
        return $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define is_ajax_request function if it doesn'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';
    }
}

// Define json_success function if it doesn't exist
if (!function_exists('json_success')) {
    function json_success($data = []) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'data' => $data]);
        exit;
    }
}

// Define json_error function if it doesn't exist
if (!function_exists('json_error')) {
    function json_error($message) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => $message]);
        exit;
    }
}

// Define begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.purchases.manage');
}

// Set page title
$page_title = 'Create Purchase Order';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get suppliers for dropdown
$suppliers = [];
if (function_exists('db_fetch_all')) {
    try {
        $suppliers = db_fetch_all("SELECT supplier_id, supplier_name FROM suppliers WHERE is_active = 1 ORDER BY supplier_name") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching suppliers: " . $e->getMessage());
    }
}

// Get products for dropdown (stock items only)
$products = [];
if (function_exists('db_fetch_all')) {
    try {
        $products = db_fetch_all("
            SELECT p.*, c.category_name 
            FROM pos_products p
            JOIN pos_categories c ON p.category_id = c.category_id
            WHERE p.stock_item = 1 AND p.is_active = 1
            ORDER BY c.category_name, p.product_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching products: " . $e->getMessage());
    }
}

// Initialize session cart if not exists
if (!isset($_SESSION['po_cart'])) {
    $_SESSION['po_cart'] = [];
}

// Handle AJAX requests
if (function_exists('is_ajax_request') && is_ajax_request()) {
    $action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');
    
    switch ($action) {
        case 'add_item':
            $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
            $quantity = isset($_POST['quantity']) ? (float)$_POST['quantity'] : 1;
            $unit_price = isset($_POST['unit_price']) ? (float)$_POST['unit_price'] : 0;
            
            if (function_exists('db_fetch_one')) {
                $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
                
                if ($product) {
                    $_SESSION['po_cart'][] = [
                        'product_id' => $product_id,
                        'product_name' => $product['product_name'] ?? '',
                        'product_code' => $product['product_code'] ?? '',
                        'quantity' => $quantity,
                        'unit_price' => $unit_price
                    ];
                    json_success(['cart' => $_SESSION['po_cart']]);
                } else {
                    json_error('Product not found');
                }
            } else {
                json_error('Database function not available');
            }
            break;
            
        case 'remove_item':
            $index = isset($_POST['index']) ? (int)$_POST['index'] : 0;
            if (isset($_SESSION['po_cart'][$index])) {
                array_splice($_SESSION['po_cart'], $index, 1);
            }
            json_success(['cart' => $_SESSION['po_cart']]);
            break;
            
        case 'update_item':
            $index = isset($_POST['index']) ? (int)$_POST['index'] : 0;
            $quantity = isset($_POST['quantity']) ? (float)$_POST['quantity'] : 0;
            $unit_price = isset($_POST['unit_price']) ? (float)$_POST['unit_price'] : 0;
            
            if (isset($_SESSION['po_cart'][$index])) {
                $_SESSION['po_cart'][$index]['quantity'] = $quantity;
                $_SESSION['po_cart'][$index]['unit_price'] = $unit_price;
            }
            json_success(['cart' => $_SESSION['po_cart']]);
            break;
            
        case 'clear_cart':
            $_SESSION['po_cart'] = [];
            json_success(['cart' => []]);
            break;
            
        case 'get_cart':
            json_success(['cart' => $_SESSION['po_cart']]);
            break;
    }
    exit;
}

// Handle form submission
$errors = [];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_po'])) {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $supplier_id = isset($_POST['supplier_id']) ? (int)$_POST['supplier_id'] : 0;
        $order_date = isset($_POST['order_date']) ? sanitize_input($_POST['order_date']) : date('Y-m-d');
        $expected_date = !empty($_POST['expected_date']) ? sanitize_input($_POST['expected_date']) : null;
        $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        if (!$supplier_id) {
            $errors[] = 'Please select a supplier';
        }
        
        if (empty($_SESSION['po_cart'])) {
            $errors[] = 'Please add at least one item to the order';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Calculate totals
                $subtotal = 0;
                foreach ($_SESSION['po_cart'] as $item) {
                    $subtotal += ($item['quantity'] ?? 0) * ($item['unit_price'] ?? 0);
                }
                
                // Generate PO number
                $po_number = 'PO-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                // Create purchase order
                $po_id = null;
                if (function_exists('db_insert')) {
                    $po_id = db_insert('purchase_orders', [
                        'po_number' => $po_number,
                        'supplier_id' => $supplier_id,
                        'order_date' => $order_date,
                        'expected_date' => $expected_date,
                        'status' => 'ordered',
                        'subtotal' => $subtotal,
                        'total_amount' => $subtotal, // No tax for now
                        'notes' => $notes ?: null,
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // Add items - FIXED: Removed total_price as it's a GENERATED column
                if ($po_id && function_exists('db_insert')) {
                    foreach ($_SESSION['po_cart'] as $item) {
                        // total_price is not included because it's a STORED GENERATED column
                        // MySQL will automatically calculate it as quantity_ordered * unit_price
                        $item_data = [
                            'po_id' => $po_id,
                            'product_id' => $item['product_id'] ?? 0,
                            'quantity_ordered' => $item['quantity'] ?? 0,
                            'unit_price' => $item['unit_price'] ?? 0
                            // 'total_price' is intentionally omitted - it's generated by MySQL
                        ];
                        
                        error_log("Inserting purchase order item: " . print_r($item_data, true));
                        $result = db_insert('purchase_order_items', $item_data);
                        
                        if (!$result) {
                            throw new Exception("Failed to insert purchase order item for product ID: " . ($item['product_id'] ?? 0));
                        }
                    }
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_CREATE, 'purchase_orders', $po_id, null, [
                        'supplier_id' => $supplier_id,
                        'total' => $subtotal,
                        'items' => count($_SESSION['po_cart'])
                    ]);
                }
                
                // Clear cart
                $_SESSION['po_cart'] = [];
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Purchase order created successfully');
                }
                
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $po_id);
                } else {
                    header('Location: view.php?id=' . $po_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create purchase order: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("PO creation failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Create Purchase Order</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .product-item {
                cursor: pointer;
                transition: background-color 0.2s;
            }
            .product-item:hover {
                background-color: #f0f0f0;
            }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .text-end { text-align: right; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Create Purchase Order</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Create Purchase Order</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/inventory/dashboard.php">Inventory</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Purchase Orders</a></li>
                    <li class="breadcrumb-item active">Create PO</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Error Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Order Form -->
            <div class="col-md-4">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Order Information
                        </h3>
                    </div>
                    
                    <form method="POST" id="poForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        <input type="hidden" name="submit_po" value="1">
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="supplier_id">Supplier <span class="text-danger">*</span></label>
                                <select class="form-select select2" id="supplier_id" name="supplier_id" required>
                                    <option value="">Select Supplier</option>
                                    <?php foreach ($suppliers as $supplier): ?>
                                        <option value="<?php echo $supplier['supplier_id'] ?? 0; ?>" <?php echo (isset($_GET['supplier_id']) && $_GET['supplier_id'] == ($supplier['supplier_id'] ?? 0)) ? 'selected' : ''; ?>>
                                            <?php echo escape_html($supplier['supplier_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="order_date">Order Date</label>
                                        <input type="date" class="form-control" id="order_date" name="order_date" 
                                               value="<?php echo date('Y-m-d'); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="expected_date">Expected Date</label>
                                        <input type="date" class="form-control" id="expected_date" name="expected_date" 
                                               value="<?php echo date('Y-m-d', strtotime('+7 days')); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Product Selection -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-box me-1"></i>
                            Add Products
                        </h3>
                    </div>
                    
                    <div class="card-body">
                        <div class="form-group mb-3">
                            <label for="product_search">Search Products</label>
                            <input type="text" class="form-control" id="product_search" 
                                   placeholder="Type to search...">
                        </div>
                        
                        <div class="product-list" style="max-height: 300px; overflow-y: auto;">
                            <?php foreach ($products as $product): ?>
                                <div class="product-item p-2 border-bottom" 
                                     onclick="selectProduct(<?php echo $product['product_id'] ?? 0; ?>, '<?php echo escape_html($product['product_name'] ?? ''); ?>', <?php echo $product['cost_price'] ?? 0; ?>)">
                                    <strong><?php echo escape_html($product['product_name'] ?? ''); ?></strong>
                                    <br>
                                    <small class="text-muted">
                                        <?php echo escape_html($product['product_code'] ?? ''); ?> | 
                                        Current Stock: <?php echo $product['current_stock'] ?? 0; ?> <?php echo escape_html($product['unit_of_measure'] ?? ''); ?>
                                    </small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Cart -->
            <div class="col-md-8">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-shopping-cart me-1"></i>
                            Order Items
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-danger" onclick="clearCart()">
                                <i class="fas fa-trash"></i> Clear All
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped" id="cartTable">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-end">Unit Price</th>
                                        <th class="text-end">Total</th>
                                        <th width="50"></th>
                                    </tr>
                                </thead>
                                <tbody id="cartBody">
                                    <!-- Cart items will be loaded here -->
                                </tbody>
                                <tfoot>
                                    <tr class="table-active">
                                        <th colspan="3" class="text-end">Subtotal:</th>
                                        <th class="text-end" id="cartSubtotal"><?php echo CURRENCY_SYMBOL; ?>0.00</th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    
                    <div class="card-footer">
                        <button type="button" class="btn btn-success" onclick="submitPO()">
                            <i class="fas fa-save me-1"></i> Create Purchase Order
                        </button>
                        <a href="index.php" class="btn btn-secondary">
                            <i class="fas fa-times me-1"></i> Cancel
                        </a>
                    </div>
                </div>

                <!-- Product Selection Modal -->
                <div class="modal fade" id="productModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-info text-white">
                                <h5 class="modal-title">Add Product</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" id="selected_product_id">
                                
                                <div class="form-group mb-3">
                                    <label>Product</label>
                                    <input type="text" class="form-control" id="selected_product_name" readonly>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="modal_quantity">Quantity</label>
                                            <input type="number" class="form-control" id="modal_quantity" value="1" min="0.01" step="0.01">
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="modal_unit_price">Unit Price</label>
                                            <div class="input-group">
                                                <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                                <input type="number" class="form-control" id="modal_unit_price" step="0.01" min="0">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-primary" onclick="addToCart()">Add to Order</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
let currentProduct = {};

$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // Load cart
    loadCart();
    
    // Product search
    $('#product_search').on('input', function() {
        const query = $(this).val().toLowerCase();
        $('.product-item').each(function() {
            const text = $(this).text().toLowerCase();
            if (text.indexOf(query) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
});

function selectProduct(productId, productName, defaultPrice) {
    $('#selected_product_id').val(productId);
    $('#selected_product_name').val(productName);
    $('#modal_quantity').val(1);
    $('#modal_unit_price').val(defaultPrice || 0);
    
    // Initialize Bootstrap 5 modal
    const productModal = new bootstrap.Modal(document.getElementById('productModal'));
    productModal.show();
}

function addToCart() {
    const productId = $('#selected_product_id').val();
    const productName = $('#selected_product_name').val();
    const quantity = parseFloat($('#modal_quantity').val());
    const unitPrice = parseFloat($('#modal_unit_price').val());
    
    if (!quantity || quantity <= 0) {
        alert('Please enter a valid quantity');
        return;
    }
    
    if (!unitPrice || unitPrice <= 0) {
        alert('Please enter a valid unit price');
        return;
    }
    
    $.post(window.location.href, {
        action: 'add_item',
        product_id: productId,
        quantity: quantity,
        unit_price: unitPrice,
        csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
    }, function(response) {
        if (response.status === 'success') {
            // Hide modal using Bootstrap 5
            const productModal = bootstrap.Modal.getInstance(document.getElementById('productModal'));
            productModal.hide();
            loadCart();
        } else {
            alert('Failed to add item: ' + (response.message || 'Unknown error'));
        }
    }).fail(function(xhr) {
        alert('Failed to add item: ' + (xhr.responseJSON?.message || 'Network error'));
    });
}

function loadCart() {
    $.get(window.location.href, { action: 'get_cart' }, function(response) {
        if (response.status === 'success') {
            renderCart(response.data.cart || []);
        }
    });
}

function renderCart(cart) {
    const tbody = $('#cartBody');
    tbody.empty();
    
    let subtotal = 0;
    
    cart.forEach((item, index) => {
        const total = (item.quantity || 0) * (item.unit_price || 0);
        subtotal += total;
        
        tbody.append(`
            <tr>
                <td>
                    <strong>${escapeHtml(item.product_name || '')}</strong>
                    <br>
                    <small class="text-muted">${escapeHtml(item.product_code || '')}</small>
                </td>
                <td class="text-center">
                    <input type="number" class="form-control form-control-sm text-center" 
                           value="${item.quantity || 0}" min="0.01" step="0.01"
                           onchange="updateItem(${index}, this.value, ${item.unit_price || 0})">
                </td>
                <td class="text-end">
                    <input type="number" class="form-control form-control-sm text-end" 
                           value="${(item.unit_price || 0).toFixed(2)}" min="0" step="0.01"
                           onchange="updateItem(${index}, ${item.quantity || 0}, this.value)">
                </td>
                <td class="text-end">${formatCurrency(total)}</td>
                <td class="text-center">
                    <button class="btn btn-sm btn-danger" onclick="removeItem(${index})">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            </tr>
        `);
    });
    
    $('#cartSubtotal').text(formatCurrency(subtotal));
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function updateItem(index, quantity, unitPrice) {
    $.post(window.location.href, {
        action: 'update_item',
        index: index,
        quantity: quantity,
        unit_price: unitPrice,
        csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
    }, function(response) {
        if (response.status === 'success') {
            loadCart();
        }
    }).fail(function() {
        alert('Failed to update item');
    });
}

function removeItem(index) {
    if (confirm('Remove this item from order?')) {
        $.post(window.location.href, {
            action: 'remove_item',
            index: index,
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
        }, function(response) {
            if (response.status === 'success') {
                loadCart();
            }
        }).fail(function() {
            alert('Failed to remove item');
        });
    }
}

function clearCart() {
    if (confirm('Clear all items from order?')) {
        $.post(window.location.href, {
            action: 'clear_cart',
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
        }, function(response) {
            if (response.status === 'success') {
                loadCart();
            }
        }).fail(function() {
            alert('Failed to clear cart');
        });
    }
}

function submitPO() {
    const supplierId = $('#supplier_id').val();
    
    if (!supplierId) {
        alert('Please select a supplier');
        return;
    }
    
    const cartRows = $('#cartBody tr').length;
    if (cartRows === 0) {
        alert('Please add at least one item to the order');
        return;
    }
    
    $('#poForm').submit();
}

function formatCurrency(amount) {
    return '<?php echo CURRENCY_SYMBOL; ?>' + amount.toFixed(2);
}
</script>

<style>
.product-item {
    cursor: pointer;
    transition: background-color 0.2s;
}
.product-item:hover {
    background-color: #f0f0f0;
}
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>