<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Stock Transfers Between Outlets - 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/
$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/ -> /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_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return '';
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        if ($diff < 2592000) return floor($diff / 86400) . ' days ago';
        return date('M d, Y', $time);
    }
}

// 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('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

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

// Set page title
$page_title = 'Stock Transfers';

// 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 outlets for dropdown
$outlets = [];
if (function_exists('db_fetch_all')) {
    try {
        $outlets = db_fetch_all("SELECT outlet_id, outlet_name FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching outlets: " . $e->getMessage());
    }
}

// Get products for dropdown
$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());
    }
}

// Handle form submission for new transfer
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'transfer') {
            $from_outlet = isset($_POST['from_outlet']) ? (int)$_POST['from_outlet'] : 0;
            $to_outlet = isset($_POST['to_outlet']) ? (int)$_POST['to_outlet'] : 0;
            $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
            $quantity = isset($_POST['quantity']) ? (float)$_POST['quantity'] : 0;
            $reason = isset($_POST['reason']) ? sanitize_input($_POST['reason']) : '';
            
            if (!$from_outlet) {
                $errors[] = 'Please select source outlet';
            }
            
            if (!$to_outlet) {
                $errors[] = 'Please select destination outlet';
            }
            
            if ($from_outlet == $to_outlet) {
                $errors[] = 'Source and destination outlets cannot be the same';
            }
            
            if (!$product_id) {
                $errors[] = 'Please select a product';
            }
            
            if ($quantity <= 0) {
                $errors[] = 'Quantity must be greater than 0';
            }
            
            // Check stock availability
            if (empty($errors)) {
                $product = null;
                if (function_exists('db_fetch_one')) {
                    try {
                        $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
                    } catch (Exception $e) {
                        error_log("Error fetching product: " . $e->getMessage());
                    }
                }
                
                if (!$product) {
                    $errors[] = 'Product not found';
                } elseif (($product['current_stock'] ?? 0) < $quantity) {
                    $errors[] = "Insufficient stock. Available: {$product['current_stock']} " . ($product['unit_of_measure'] ?? 'units');
                }
            }
            
            if (empty($errors)) {
                try {
                    if (function_exists('begin_transaction')) {
                        begin_transaction();
                    }
                    
                    // Reduce stock from source outlet
                    if (function_exists('db_query')) {
                        db_query("
                            UPDATE pos_products 
                            SET current_stock = current_stock - ? 
                            WHERE product_id = ?
                        ", [$quantity, $product_id]);
                    }
                    
                    // Record stock movement (out)
                    if (function_exists('db_insert')) {
                        db_insert('stock_movements', [
                            'product_id' => $product_id,
                            'movement_type' => 'transfer_out',
                            'quantity' => -$quantity,
                            'reference_type' => 'transfer',
                            'notes' => "Transfer to outlet #$to_outlet" . ($reason ? ": $reason" : ''),
                            'created_by' => $user_id,
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                    
                    // Add stock to destination outlet (in a real system, you might have separate stock per outlet)
                    // For now, we're using the same product table, so we just record the inbound movement
                    if (function_exists('db_insert')) {
                        db_insert('stock_movements', [
                            'product_id' => $product_id,
                            'movement_type' => 'transfer_in',
                            'quantity' => $quantity,
                            'reference_type' => 'transfer',
                            'notes' => "Transfer from outlet #$from_outlet" . ($reason ? ": $reason" : ''),
                            'created_by' => $user_id,
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                    
                    // Audit log
                    if (function_exists('audit_log')) {
                        audit_log($user_id, 'stock_transfer', 'pos_products', $product_id, null, [
                            'from_outlet' => $from_outlet,
                            'to_outlet' => $to_outlet,
                            'quantity' => $quantity,
                            'reason' => $reason
                        ]);
                    }
                    
                    if (function_exists('commit_transaction')) {
                        commit_transaction();
                    }
                    
                    if (function_exists('set_flash_message')) {
                        set_flash_message('success', 'Stock transferred successfully');
                    }
                    
                    if (function_exists('redirect')) {
                        redirect('transfers.php');
                    } else {
                        header('Location: transfers.php');
                        exit;
                    }
                    
                } catch (Exception $e) {
                    if (function_exists('rollback_transaction')) {
                        rollback_transaction();
                    }
                    $errors[] = 'Failed to transfer stock: ' . $e->getMessage();
                    if (function_exists('log_message')) {
                        log_message("Transfer failed: " . $e->getMessage(), 'ERROR');
                    }
                }
            }
        }
    }
}

// Get transfer history (from stock movements)
$transfers = [];
if (function_exists('db_fetch_all')) {
    try {
        $transfers = db_fetch_all("
            SELECT 
                sm.*,
                p.product_name, p.product_code, p.unit_of_measure,
                u.first_name, u.last_name
            FROM stock_movements sm
            JOIN pos_products p ON sm.product_id = p.product_id
            LEFT JOIN users u ON sm.created_by = u.user_id
            WHERE sm.movement_type IN ('transfer_out', 'transfer_in')
            ORDER BY sm.created_at DESC
            LIMIT 50
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching transfers: " . $e->getMessage());
    }
}

// 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>Stock Transfers</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; }
            .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="#">Stock Transfers</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">Stock Transfers</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="movements.php">Stock Movements</a></li>
                    <li class="breadcrumb-item active">Transfers</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">
            <!-- Transfer Form -->
            <div class="col-md-5">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exchange-alt me-1"></i>
                            New Stock Transfer
                        </h3>
                    </div>
                    
                    <form method="POST" id="transferForm">
                        <?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="action" value="transfer">
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="from_outlet">From Outlet <span class="text-danger">*</span></label>
                                <select class="form-select" id="from_outlet" name="from_outlet" required>
                                    <option value="">Select Source Outlet</option>
                                    <?php foreach ($outlets as $outlet): ?>
                                        <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>">
                                            <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="to_outlet">To Outlet <span class="text-danger">*</span></label>
                                <select class="form-select" id="to_outlet" name="to_outlet" required>
                                    <option value="">Select Destination Outlet</option>
                                    <?php foreach ($outlets as $outlet): ?>
                                        <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>">
                                            <?php echo escape_html($outlet['outlet_name'] ?? ''); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="product_id">Product <span class="text-danger">*</span></label>
                                <select class="form-select select2" id="product_id" name="product_id" required>
                                    <option value="">Select Product</option>
                                    <?php foreach ($products as $product): ?>
                                        <option value="<?php echo $product['product_id'] ?? 0; ?>" 
                                                data-stock="<?php echo $product['current_stock'] ?? 0; ?>"
                                                data-unit="<?php echo $product['unit_of_measure'] ?? ''; ?>">
                                            <?php echo escape_html($product['product_name'] ?? ''); ?> 
                                            (<?php echo escape_html($product['product_code'] ?? ''); ?>) - 
                                            Current: <?php echo $product['current_stock'] ?? 0; ?> <?php echo $product['unit_of_measure'] ?? ''; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="quantity">Quantity <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="quantity" name="quantity" 
                                       step="0.01" min="0" required>
                                <small class="text-muted" id="stock_warning"></small>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="reason">Reason for Transfer</label>
                                <textarea class="form-control" id="reason" name="reason" rows="2"></textarea>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Note:</strong> Transferring stock will reduce inventory from source outlet and increase it in destination.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-exchange-alt me-1"></i> Transfer Stock
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Transfer History -->
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Recent Transfers
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($transfers)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-exchange-alt fa-3x mb-3"></i>
                                <p>No transfers recorded</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date/Time</th>
                                            <th>Product</th>
                                            <th>Type</th>
                                            <th class="text-end">Quantity</th>
                                            <th>Notes</th>
                                            <th>By</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($transfers as $transfer): ?>
                                        <tr class="<?php echo ($transfer['movement_type'] ?? '') == 'transfer_in' ? 'table-success' : 'table-warning'; ?>">
                                            <td>
                                                <?php echo isset($transfer['created_at']) ? date('M d, Y H:i', strtotime($transfer['created_at'])) : 'N/A'; ?>
                                                <br>
                                                <small class="text-muted"><?php echo isset($transfer['created_at']) ? time_ago($transfer['created_at']) : ''; ?></small>
                                            </td>
                                            <td>
                                                <strong><?php echo escape_html($transfer['product_name'] ?? ''); ?></strong>
                                                <br>
                                                <small class="text-muted"><?php echo escape_html($transfer['product_code'] ?? ''); ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo ($transfer['movement_type'] ?? '') == 'transfer_in' ? 'success' : 'warning'; ?>">
                                                    <?php echo ($transfer['movement_type'] ?? '') == 'transfer_in' ? 'Received' : 'Sent'; ?>
                                                </span>
                                            </td>
                                            <td class="text-end">
                                                <span class="badge bg-<?php echo ($transfer['quantity'] ?? 0) > 0 ? 'success' : 'danger'; ?>">
                                                    <?php echo ($transfer['quantity'] ?? 0) > 0 ? '+' : ''; ?><?php echo $transfer['quantity'] ?? 0; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <small><?php echo escape_html($transfer['notes'] ?: '-'); ?></small>
                                            </td>
                                            <td>
                                                <small><?php echo escape_html($transfer['first_name'] ?? ''); ?></small>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // Show stock warning when product selected
    $('#product_id').on('change', function() {
        const selected = $(this).find(':selected');
        const stock = selected.data('stock');
        const unit = selected.data('unit');
        
        if (stock !== undefined) {
            $('#stock_warning').text(`Available stock: ${stock} ${unit}`);
            
            // Update max attribute
            $('#quantity').attr('max', stock);
        } else {
            $('#stock_warning').text('');
            $('#quantity').removeAttr('max');
        }
    });
    
    // Validate quantity
    $('#quantity').on('input', function() {
        const max = $(this).attr('max');
        const value = parseFloat($(this).val()) || 0;
        
        if (max && value > parseFloat(max)) {
            $(this).val(max);
            alert(`Maximum available quantity is ${max}`);
        }
    });
});

// Form validation
$('#transferForm').on('submit', function(e) {
    const fromOutlet = $('#from_outlet').val();
    const toOutlet = $('#to_outlet').val();
    const product = $('#product_id').val();
    const quantity = parseFloat($('#quantity').val()) || 0;
    
    if (fromOutlet === toOutlet) {
        e.preventDefault();
        alert('Source and destination outlets cannot be the same');
        return false;
    }
    
    if (!quantity || quantity <= 0) {
        e.preventDefault();
        alert('Please enter a valid quantity');
        return false;
    }
    
    return confirm('Process this stock transfer?');
});
</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>';
}
?>