<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Receive 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 format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// 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 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 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 db_query function if it doesn't exist
if (!function_exists('db_query')) {
    function db_query($sql, $params = []) {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $stmt = $db->prepare($sql);
                return $stmt->execute($params);
            }
        }
        return false;
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

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

// Set page title
$page_title = 'Receive 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 PO ID from URL
$po_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$po_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid PO ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get PO data
$po = [];
if (function_exists('db_fetch_one')) {
    try {
        $po = db_fetch_one("
            SELECT po.*, s.supplier_name
            FROM purchase_orders po
            JOIN suppliers s ON po.supplier_id = s.supplier_id
            WHERE po.po_id = ?
        ", [$po_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching PO: " . $e->getMessage());
    }
}

if (empty($po)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Purchase order not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Check if PO can be received
if (($po['status'] ?? '') == 'received') {
    if (function_exists('set_flash_message')) {
        set_flash_message('warning', 'This purchase order has already been fully received');
    }
    if (function_exists('redirect')) {
        redirect('view.php?id=' . $po_id);
    } else {
        header('Location: view.php?id=' . $po_id);
        exit;
    }
}

if (($po['status'] ?? '') == 'cancelled') {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Cannot receive a cancelled purchase order');
    }
    if (function_exists('redirect')) {
        redirect('view.php?id=' . $po_id);
    } else {
        header('Location: view.php?id=' . $po_id);
        exit;
    }
}

// Get PO items
$items = [];
if (function_exists('db_fetch_all')) {
    try {
        $items = db_fetch_all("
            SELECT 
                poi.*,
                p.product_name, p.product_code, p.unit_of_measure,
                p.current_stock
            FROM purchase_order_items poi
            JOIN pos_products p ON poi.product_id = p.product_id
            WHERE poi.po_id = ?
        ", [$po_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching PO items: " . $e->getMessage());
    }
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $received_items = $_POST['received'] ?? [];
        $received_quantities = $_POST['quantity'] ?? [];
        $received_notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        $all_received = true;
        $any_received = false;
        
        foreach ($items as $item) {
            $item_id = $item['item_id'] ?? 0;
            $received_qty = isset($received_items[$item_id]) ? (float)($received_quantities[$item_id] ?? 0) : 0;
            
            if ($received_qty > 0) {
                $any_received = true;
                if ($received_qty < ($item['quantity_ordered'] ?? 0)) {
                    $all_received = false;
                }
            } else {
                if (($item['quantity_received'] ?? 0) < ($item['quantity_ordered'] ?? 0)) {
                    $all_received = false;
                }
            }
        }
        
        if (!$any_received) {
            $errors[] = 'Please enter at least one item to receive';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $total_received = 0;
                
                foreach ($items as $item) {
                    $item_id = $item['item_id'] ?? 0;
                    $ordered_qty = $item['quantity_ordered'] ?? 0;
                    $prev_received = $item['quantity_received'] ?? 0;
                    $received_qty = isset($received_items[$item_id]) ? (float)($received_quantities[$item_id] ?? 0) : 0;
                    
                    if ($received_qty > 0) {
                        $new_received = $prev_received + $received_qty;
                        
                        if ($new_received > $ordered_qty) {
                            throw new Exception("Cannot receive more than ordered quantity for {$item['product_name']}");
                        }
                        
                        // Update PO item
                        if (function_exists('db_update')) {
                            db_update('purchase_order_items', [
                                'quantity_received' => $new_received
                            ], 'item_id = ?', [$item_id]);
                        }
                        
                        // Update product stock
                        if (function_exists('db_query')) {
                            db_query("
                                UPDATE pos_products 
                                SET current_stock = current_stock + ? 
                                WHERE product_id = ?
                            ", [$received_qty, $item['product_id'] ?? 0]);
                        }
                        
                        // Record stock movement
                        if (function_exists('db_insert')) {
                            db_insert('stock_movements', [
                                'product_id' => $item['product_id'] ?? 0,
                                'movement_type' => 'purchase',
                                'quantity' => $received_qty,
                                'reference_type' => 'purchase_order',
                                'reference_id' => $po_id,
                                'notes' => "Received from PO #{$po['po_number']}",
                                'created_by' => $user_id,
                                'created_at' => date(DATETIME_FORMAT)
                            ]);
                        }
                        
                        $total_received++;
                    }
                }
                
                // Update PO status
                $new_status = $all_received ? 'received' : 'partial';
                
                if (function_exists('db_update')) {
                    db_update('purchase_orders', [
                        'status' => $new_status,
                        'received_by' => $user_id,
                        'received_at' => date(DATETIME_FORMAT),
                        'notes' => $received_notes ?: ($po['notes'] ?? '')
                    ], 'po_id = ?', [$po_id]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'receive_po', 'purchase_orders', $po_id, 
                             ['status' => $po['status'] ?? ''], 
                             ['status' => $new_status, 'items_received' => $total_received]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Purchase order received 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 receive order: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("PO receive 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>Receive Purchase Order</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.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>
        <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; }
            .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="#">Receive 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">Receive Purchase Order: <?php echo htmlspecialchars($po['po_number'] ?? 'N/A'); ?></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"><a href="view.php?id=<?php echo $po_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Receive</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">
            <div class="col-md-12">
                <!-- PO Summary -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Order Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <strong>PO Number:</strong><br>
                                <?php echo htmlspecialchars($po['po_number'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Supplier:</strong><br>
                                <?php echo escape_html($po['supplier_name'] ?? 'N/A'); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Order Date:</strong><br>
                                <?php echo isset($po['order_date']) ? date('M d, Y', strtotime($po['order_date'])) : 'N/A'; ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Expected Date:</strong><br>
                                <?php echo !empty($po['expected_date']) ? date('M d, Y', strtotime($po['expected_date'])) : 'Not specified'; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Receive Form -->
                <form method="POST" id="receiveForm">
                    <?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; ?>
                    
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-truck me-1"></i>
                                Items to Receive
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-sm btn-info" onclick="receiveAll()">
                                    <i class="fas fa-check-double"></i> Receive All
                                </button>
                                <button type="button" class="btn btn-sm btn-secondary" onclick="clearAll()">
                                    <i class="fas fa-times"></i> Clear All
                                </button>
                            </div>
                        </div>
                        
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th width="30">
                                                <input type="checkbox" id="selectAll" onchange="toggleAll()">
                                            </th>
                                            <th>Product</th>
                                            <th class="text-center">Ordered</th>
                                            <th class="text-center">Previously Received</th>
                                            <th class="text-center">Remaining</th>
                                            <th class="text-center">Receive Now</th>
                                            <th class="text-end">Unit Price</th>
                                            <th class="text-end">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($items as $item): 
                                            $ordered_qty = $item['quantity_ordered'] ?? 0;
                                            $received_qty = $item['quantity_received'] ?? 0;
                                            $remaining = $ordered_qty - $received_qty;
                                        ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="received[<?php echo $item['item_id'] ?? 0; ?>]" 
                                                       value="1" class="item-checkbox" data-item="<?php echo $item['item_id'] ?? 0; ?>"
                                                       onchange="toggleReceive(<?php echo $item['item_id'] ?? 0; ?>)"
                                                       <?php echo $remaining > 0 ? '' : 'disabled'; ?>>
                                            </td>
                                            <td>
                                                <strong><?php echo escape_html($item['product_name'] ?? ''); ?></strong>
                                                <br>
                                                <small class="text-muted"><?php echo escape_html($item['product_code'] ?? ''); ?></small>
                                            </td>
                                            <td class="text-center"><?php echo $ordered_qty; ?></td>
                                            <td class="text-center"><?php echo $received_qty; ?></td>
                                            <td class="text-center">
                                                <span class="badge bg-<?php echo $remaining > 0 ? 'warning' : 'success'; ?>">
                                                    <?php echo $remaining; ?>
                                                </span>
                                            </td>
                                            <td class="text-center" style="min-width: 120px;">
                                                <input type="number" 
                                                       name="quantity[<?php echo $item['item_id'] ?? 0; ?>]" 
                                                       id="qty_<?php echo $item['item_id'] ?? 0; ?>"
                                                       class="form-control form-control-sm text-center"
                                                       value="<?php echo $remaining; ?>"
                                                       min="0" max="<?php echo $remaining; ?>"
                                                       step="0.01"
                                                       <?php echo $remaining > 0 ? '' : 'disabled'; ?>>
                                            </td>
                                            <td class="text-end"><?php echo format_currency($item['unit_price'] ?? 0); ?></td>
                                            <td class="text-end">
                                                <?php echo format_currency(($item['unit_price'] ?? 0) * $ordered_qty); ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="notes">Receiving Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"><?php echo escape_html($po['notes'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Note:</strong> Receiving items will update inventory stock levels.
                                Make sure to verify quantities before confirming.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-check-circle me-1"></i> Confirm Receipt
                            </button>
                            <a href="view.php?id=<?php echo $po_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize checkboxes
    updateSelectAll();
});

function toggleAll() {
    const checked = $('#selectAll').prop('checked');
    $('.item-checkbox:enabled').each(function() {
        $(this).prop('checked', checked);
        const itemId = $(this).data('item');
        toggleReceive(itemId);
    });
}

function toggleReceive(itemId) {
    const checkbox = $('input[name="received[' + itemId + ']"]');
    const qtyField = $('#qty_' + itemId);
    
    if (checkbox.prop('checked')) {
        qtyField.prop('disabled', false);
    } else {
        qtyField.prop('disabled', true).val(0);
    }
    
    updateSelectAll();
}

function updateSelectAll() {
    const total = $('.item-checkbox:enabled').length;
    const checked = $('.item-checkbox:enabled:checked').length;
    
    if (total > 0 && checked === total) {
        $('#selectAll').prop('checked', true).prop('indeterminate', false);
    } else if (checked > 0) {
        $('#selectAll').prop('checked', false).prop('indeterminate', true);
    } else {
        $('#selectAll').prop('checked', false).prop('indeterminate', false);
    }
}

function receiveAll() {
    $('.item-checkbox:enabled').each(function() {
        $(this).prop('checked', true);
        const itemId = $(this).data('item');
        $('#qty_' + itemId).prop('disabled', false);
    });
    updateSelectAll();
}

function clearAll() {
    $('.item-checkbox:enabled').each(function() {
        $(this).prop('checked', false);
        const itemId = $(this).data('item');
        $('#qty_' + itemId).prop('disabled', true).val(0);
    });
    updateSelectAll();
}

// Form validation
$('#receiveForm').on('submit', function(e) {
    const checked = $('.item-checkbox:checked').length;
    
    if (checked === 0) {
        e.preventDefault();
        alert('Please select at least one item to receive');
        return false;
    }
    
    let hasQuantity = false;
    $('.item-checkbox:checked').each(function() {
        const itemId = $(this).data('item');
        const qty = parseFloat($('#qty_' + itemId).val()) || 0;
        if (qty > 0) {
            hasQuantity = true;
        }
    });
    
    if (!hasQuantity) {
        e.preventDefault();
        alert('Please enter quantities for selected items');
        return false;
    }
    
    return confirm('Confirm receipt of selected items? This will update inventory levels.');
});
</script>

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