<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Stock Adjustments - 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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_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 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 constants if not defined
if (!defined('ITEMS_PER_PAGE')) {
    define('ITEMS_PER_PAGE', 25);
}
if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}

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

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

// 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 filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 25;

// Build where clause for adjustments list
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (sa.adjustment_number LIKE ? OR sa.reason LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term]);
}

if (!empty($date_from)) {
    $where .= " AND DATE(sa.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where .= " AND DATE(sa.created_at) <= ?";
    $params[] = $date_to;
}

// Get adjustments
$adjustments = [];
$total = 0;

if (function_exists('db_fetch_value') && function_exists('db_fetch_all')) {
    try {
        // Get total count
        $count_sql = "SELECT COUNT(*) FROM stock_adjustments sa WHERE $where";
        $total = db_fetch_value($count_sql, $params) ?: 0;

        // Get paginated data
        $offset = ($page - 1) * $per_page;
        
        $sql = "
            SELECT 
                sa.*,
                u.first_name, u.last_name,
                au.first_name as approved_first, au.last_name as approved_last,
                COUNT(sai.item_id) as item_count
            FROM stock_adjustments sa
            LEFT JOIN users u ON sa.created_by = u.user_id
            LEFT JOIN users au ON sa.approved_by = au.user_id
            LEFT JOIN stock_adjustment_items sai ON sa.adjustment_id = sai.adjustment_id
            WHERE $where
            GROUP BY sa.adjustment_id
            ORDER BY sa.created_at DESC
            LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
        
        $adjustments = db_fetch_all($sql, $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching adjustments: " . $e->getMessage());
    }
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 0;

// Get products for dropdown
$products = [];
if (function_exists('db_fetch_all')) {
    try {
        $products = db_fetch_all("
            SELECT product_id, product_name, product_code, current_stock, unit_of_measure
            FROM pos_products 
            WHERE stock_item = 1 AND is_active = 1
            ORDER BY product_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching products: " . $e->getMessage());
    }
}

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

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 === 'create') {
            $adjustment_type = isset($_POST['adjustment_type']) ? sanitize_input($_POST['adjustment_type']) : 'positive';
            $reason = isset($_POST['reason']) ? sanitize_input($_POST['reason']) : '';
            $other_reason = isset($_POST['other_reason']) ? sanitize_input($_POST['other_reason']) : '';
            $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
            $products_data = $_POST['products'] ?? [];
            $quantities = $_POST['quantities'] ?? [];
            
            if ($reason === 'Other' && !empty($other_reason)) {
                $reason = $other_reason;
            }
            
            if (empty($reason)) {
                $errors[] = 'Reason is required';
            }
            
            $has_items = false;
            foreach ($products_data as $product_id) {
                $qty = isset($quantities[$product_id]) ? (float)$quantities[$product_id] : 0;
                if ($qty != 0) {
                    $has_items = true;
                    break;
                }
            }
            
            if (!$has_items) {
                $errors[] = 'Please enter at least one non-zero adjustment';
            }
            
            if (empty($errors)) {
                try {
                    if (function_exists('begin_transaction')) {
                        begin_transaction();
                    }
                    
                    // Create adjustment record
                    $adjustment_number = 'ADJ-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                    
                    $adjustment_id = null;
                    if (function_exists('db_insert')) {
                        $adjustment_id = db_insert('stock_adjustments', [
                            'adjustment_number' => $adjustment_number,
                            'adjustment_type' => $adjustment_type,
                            'reason' => $reason,
                            'notes' => $notes ?: null,
                            'created_by' => $user_id,
                            'created_at' => date(DATETIME_FORMAT)
                        ]);
                    }
                    
                    // Add items and update stock
                    if ($adjustment_id && function_exists('db_fetch_one') && function_exists('db_insert') && function_exists('db_update')) {
                        foreach ($products_data as $product_id) {
                            $qty = isset($quantities[$product_id]) ? (float)$quantities[$product_id] : 0;
                            
                            if ($qty == 0) continue;
                            
                            // Get current stock
                            $product = db_fetch_one("SELECT current_stock FROM pos_products WHERE product_id = ?", [$product_id]);
                            
                            // Calculate new stock
                            $adjustment_qty = $adjustment_type === 'positive' ? $qty : -$qty;
                            $new_stock = ($product['current_stock'] ?? 0) + $adjustment_qty;
                            
                            if ($new_stock < 0) {
                                throw new Exception("Insufficient stock for product ID $product_id");
                            }
                            
                            // Insert adjustment item
                            db_insert('stock_adjustment_items', [
                                'adjustment_id' => $adjustment_id,
                                'product_id' => $product_id,
                                'quantity' => $adjustment_qty,
                                'notes' => $notes
                            ]);
                            
                            // Update product stock
                            db_update('pos_products', [
                                'current_stock' => $new_stock
                            ], 'product_id = ?', [$product_id]);
                            
                            // Record stock movement
                            db_insert('stock_movements', [
                                'product_id' => $product_id,
                                'movement_type' => 'adjustment',
                                'quantity' => $adjustment_qty,
                                'reference_type' => 'adjustment',
                                'reference_id' => $adjustment_id,
                                'notes' => "Stock adjustment: $reason",
                                'created_by' => $user_id,
                                'created_at' => date(DATETIME_FORMAT)
                            ]);
                        }
                    }
                    
                    // Audit log
                    if (function_exists('audit_log')) {
                        audit_log($user_id, 'stock_adjustment', 'stock_adjustments', $adjustment_id, null, [
                            'type' => $adjustment_type,
                            'reason' => $reason
                        ]);
                    }
                    
                    if (function_exists('commit_transaction')) {
                        commit_transaction();
                    }
                    
                    if (function_exists('set_flash_message')) {
                        set_flash_message('success', 'Stock adjustment created successfully');
                    }
                    
                    if (function_exists('redirect')) {
                        redirect('adjustments.php');
                    } else {
                        header('Location: adjustments.php');
                        exit;
                    }
                    
                } catch (Exception $e) {
                    if (function_exists('rollback_transaction')) {
                        rollback_transaction();
                    }
                    $errors[] = 'Failed to create adjustment: ' . $e->getMessage();
                    if (function_exists('log_message')) {
                        log_message("Adjustment failed: " . $e->getMessage(), 'ERROR');
                    }
                }
            }
        } elseif ($action === 'approve') {
            $adjustment_id = isset($_POST['adjustment_id']) ? (int)$_POST['adjustment_id'] : 0;
            
            if ($adjustment_id && function_exists('db_update')) {
                db_update('stock_adjustments', [
                    'approved_by' => $user_id,
                    'approved_at' => date(DATETIME_FORMAT)
                ], 'adjustment_id = ?', [$adjustment_id]);
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Adjustment approved');
                }
                
                if (function_exists('redirect')) {
                    redirect('adjustments.php');
                } else {
                    header('Location: adjustments.php');
                    exit;
                }
            }
        }
    }
}

// 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 Adjustments</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="#">Stock Adjustments</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 Adjustments</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">Adjustments</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- 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; ?>

        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- New Adjustment Form -->
            <div class="col-md-5">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-balance-scale me-1"></i>
                            New Stock Adjustment
                        </h3>
                    </div>
                    
                    <form method="POST" id="adjustmentForm">
                        <?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="create">
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="adjustment_type">Adjustment Type</label>
                                <select class="form-select" id="adjustment_type" name="adjustment_type" required>
                                    <option value="positive">Positive Adjustment (Add Stock)</option>
                                    <option value="negative">Negative Adjustment (Remove Stock)</option>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="reason">Reason <span class="text-danger">*</span></label>
                                <select class="form-select" id="reason" name="reason" required>
                                    <option value="">Select Reason</option>
                                    <option value="Inventory count correction">Inventory count correction</option>
                                    <option value="Damaged goods">Damaged goods</option>
                                    <option value="Expired products">Expired products</option>
                                    <option value="Theft/loss">Theft/loss</option>
                                    <option value="Return to supplier">Return to supplier</option>
                                    <option value="Sample/display">Sample/display</option>
                                    <option value="Donation">Donation</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3" id="other_reason_group" style="display: none;">
                                <label for="other_reason">Please specify</label>
                                <input type="text" class="form-control" id="other_reason" name="other_reason">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Additional Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                            </div>
                            
                            <hr>
                            
                            <h5>Products to Adjust</h5>
                            <div id="product_list">
                                <!-- Products will be added here via JavaScript -->
                            </div>
                            
                            <button type="button" class="btn btn-sm btn-info mt-2" onclick="addProductRow()">
                                <i class="fas fa-plus"></i> Add Product
                            </button>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Save Adjustment
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Adjustments List -->
            <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 Adjustments
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($adjustments)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-balance-scale fa-3x mb-3"></i>
                                <p>No adjustments recorded</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Adjustment #</th>
                                            <th>Date</th>
                                            <th>Type</th>
                                            <th>Reason</th>
                                            <th class="text-center">Items</th>
                                            <th>Status</th>
                                            <th>Created By</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($adjustments as $adj): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($adj['adjustment_number'] ?? ''); ?></strong>
                                            </td>
                                            <td>
                                                <?php echo isset($adj['created_at']) ? date('M d, Y', strtotime($adj['created_at'])) : 'N/A'; ?>
                                                <br>
                                                <small class="text-muted"><?php echo isset($adj['created_at']) ? time_ago($adj['created_at']) : ''; ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo ($adj['adjustment_type'] ?? '') == 'positive' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($adj['adjustment_type'] ?? ''); ?>
                                                </span>
                                            </td>
                                            <td><?php echo escape_html($adj['reason'] ?? ''); ?></td>
                                            <td class="text-center"><?php echo $adj['item_count'] ?? 0; ?></td>
                                            <td>
                                                <?php if (!empty($adj['approved_by'])): ?>
                                                    <span class="badge bg-success">Approved</span>
                                                    <br>
                                                    <small>by <?php echo escape_html(($adj['approved_first'] ?? '') . ' ' . ($adj['approved_last'] ?? '')); ?></small>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Pending</span>
                                                    <?php if (function_exists('has_permission') && has_permission('inventory.stock.approve')): ?>
                                                        <form method="POST" style="display: inline;">
                                                            <?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="approve">
                                                            <input type="hidden" name="adjustment_id" value="<?php echo $adj['adjustment_id'] ?? 0; ?>">
                                                            <button type="submit" class="btn btn-sm btn-success ms-1" 
                                                                    onclick="return confirm('Approve this adjustment?')">
                                                                <i class="fas fa-check"></i>
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small><?php echo escape_html(($adj['first_name'] ?? '') . ' ' . ($adj['last_name'] ?? '')); ?></small>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <div class="card-footer clearfix">
                        <ul class="pagination pagination-sm m-0 float-end">
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Product Row Template -->
<script>
let productRowCount = 0;
const products = <?php echo json_encode($products); ?>;

function addProductRow() {
    const container = document.getElementById('product_list');
    const row = document.createElement('div');
    row.className = 'row mb-2 product-row';
    row.id = 'product_row_' + productRowCount;
    
    let options = '<option value="">Select Product</option>';
    products.forEach(p => {
        options += `<option value="${p.product_id}" data-stock="${p.current_stock}" data-unit="${p.unit_of_measure || 'units'}">${p.product_name} (${p.product_code}) - Current: ${p.current_stock}</option>`;
    });
    
    row.innerHTML = `
        <div class="col-md-7">
            <select class="form-select form-select-sm" name="products[]" required onchange="updateStockInfo(${productRowCount})">
                ${options}
            </select>
        </div>
        <div class="col-md-3">
            <input type="number" class="form-control form-control-sm" name="quantities[${productRowCount}]" 
                   placeholder="Qty" step="0.01" onchange="updatePreview()">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-sm btn-danger" onclick="removeProductRow(${productRowCount})">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="col-md-12">
            <small class="text-muted stock-info" id="stock_info_${productRowCount}"></small>
        </div>
    `;
    
    container.appendChild(row);
    productRowCount++;
}

function removeProductRow(id) {
    const row = document.getElementById('product_row_' + id);
    if (row) {
        row.remove();
    }
}

function updateStockInfo(rowId) {
    const select = document.querySelector(`#product_row_${rowId} select`);
    const stockInfo = document.getElementById(`stock_info_${rowId}`);
    const adjustmentType = document.getElementById('adjustment_type').value;
    
    if (select && select.value) {
        const selected = select.options[select.selectedIndex];
        const currentStock = selected.dataset.stock;
        const unit = selected.dataset.unit;
        
        stockInfo.textContent = `Current stock: ${currentStock} ${unit}`;
        
        if (adjustmentType === 'negative') {
            stockInfo.textContent += ` - Max removable: ${currentStock}`;
        }
    } else {
        stockInfo.textContent = '';
    }
}

// Show/hide other reason field
$(document).ready(function() {
    $('#reason').on('change', function() {
        if ($(this).val() === 'Other') {
            $('#other_reason_group').slideDown();
            $('#other_reason').prop('required', true);
        } else {
            $('#other_reason_group').slideUp();
            $('#other_reason').prop('required', false);
        }
    });
    
    // Update max values based on adjustment type
    $('#adjustment_type').on('change', function() {
        $('.product-row').each(function() {
            const rowId = this.id.split('_')[2];
            updateStockInfo(rowId);
        });
    });
});

// Form validation
$('#adjustmentForm').on('submit', function(e) {
    const reason = $('#reason').val();
    const otherReason = $('#other_reason').val();
    const productRows = $('.product-row').length;
    
    if (productRows === 0) {
        e.preventDefault();
        alert('Please add at least one product');
        return false;
    }
    
    if (reason === 'Other' && !otherReason) {
        e.preventDefault();
        alert('Please specify the reason');
        return false;
    }
    
    let hasQuantity = false;
    $('input[name^="quantities"]').each(function() {
        if (parseFloat($(this).val()) !== 0) {
            hasQuantity = true;
        }
    });
    
    if (!hasQuantity) {
        e.preventDefault();
        alert('Please enter quantities for at least one product');
        return false;
    }
    
    return confirm('Create this stock adjustment?');
});
</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>';
}
?>