<?php
include 'db.php';
include 'auth.php';
require_right('Access POS');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_station':
                $name = trim($_POST['station_name']);
                $description = trim($_POST['description']);
                $color = $_POST['color'];
                $preparation_time = intval($_POST['preparation_time']);
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("INSERT INTO kds_stations (name, description, color, preparation_time) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("sssi", $name, $description, $color, $preparation_time);
                    if ($stmt->execute()) {
                        $success_message = "Station added successfully!";
                    } else {
                        $error_message = "Error adding station: " . $stmt->error;
                    }
                }
                break;
                
            case 'update_station':
                $station_id = intval($_POST['station_id']);
                $name = trim($_POST['station_name']);
                $description = trim($_POST['description']);
                $color = $_POST['color'];
                $preparation_time = intval($_POST['preparation_time']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("UPDATE kds_stations SET name = ?, description = ?, color = ?, preparation_time = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("sssiii", $name, $description, $color, $preparation_time, $is_active, $station_id);
                    if ($stmt->execute()) {
                        $success_message = "Station updated successfully!";
                    } else {
                        $error_message = "Error updating station: " . $stmt->error;
                    }
                }
                break;
                
            case 'delete_station':
                $station_id = intval($_POST['station_id']);
                $stmt = $conn->prepare("DELETE FROM kds_stations WHERE id = ?");
                $stmt->bind_param("i", $station_id);
                if ($stmt->execute()) {
                    $success_message = "Station deleted successfully!";
                } else {
                    $error_message = "Error deleting station: " . $stmt->error;
                }
                break;
                
            case 'update_setting':
                $setting_key = $_POST['setting_key'];
                $setting_value = $_POST['setting_value'];
                
                $stmt = $conn->prepare("UPDATE kds_settings SET setting_value = ? WHERE setting_key = ?");
                $stmt->bind_param("ss", $setting_value, $setting_key);
                if ($stmt->execute()) {
                    $success_message = "Setting updated successfully!";
                } else {
                    $error_message = "Error updating setting: " . $stmt->error;
                }
                break;
        }
    }
}

// Get stations
$stations = $conn->query("SELECT * FROM kds_stations ORDER BY sort_order, name");

// Get KDS settings
$kds_settings = [];
$settings_result = $conn->query("SELECT * FROM kds_settings ORDER BY setting_key");
while ($setting = $settings_result->fetch_assoc()) {
    $kds_settings[$setting['setting_key']] = $setting;
}

// Get items for station assignment
$items = $conn->query("SELECT id, name, category_id FROM items WHERE item_role != 'material' ORDER BY name");
$categories = $conn->query("SELECT id, name FROM categories ORDER BY name");

include 'layout.php';
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Kitchen Display System (KDS) Management</h4>
                <h6>Configure KDS stations, settings, and item assignments</h6>
            </div>
            <div class="page-btn">
                <a href="kds.php" class="btn btn-primary">
                    <i class="feather feather-monitor me-2"></i>View KDS
                </a>
                <a href="pos.php" class="btn btn-secondary">
                    <i class="feather feather-arrow-left me-2"></i>Back to POS
                </a>
            </div>
        </div>

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

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="feather feather-alert-circle me-2"></i><?= htmlspecialchars($error_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Navigation Tabs -->
        <div class="card">
            <div class="card-body">
                <ul class="nav nav-tabs nav-tabs-solid nav-justified" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a class="nav-link active" data-bs-toggle="tab" href="#stations" role="tab">
                            <i class="feather feather-grid me-2"></i>Stations
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#settings" role="tab">
                            <i class="feather feather-settings me-2"></i>Settings
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#assignments" role="tab" id="assignments-tab">
                            <i class="feather feather-link me-2"></i>Item Assignments
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#cleanup" role="tab" id="cleanup-tab">
                            <i class="feather feather-trash-2 me-2"></i>Record Cleanup
                        </a>
                    </li>
                </ul>

                <div class="tab-content">
                    <!-- Stations Tab -->
                    <div class="tab-pane fade show active" id="stations" role="tabpanel">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-plus me-2"></i>Add New Station
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST">
                                            <input type="hidden" name="action" value="add_station">
                                            
                                            <div class="form-group">
                                                <label>Station Name</label>
                                                <input type="text" class="form-control" name="station_name" required>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Description</label>
                                                <textarea class="form-control" name="description" rows="3"></textarea>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Color</label>
                                                <input type="color" class="form-control form-control-color" name="color" value="#007bff">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Preparation Time (minutes)</label>
                                                <input type="number" class="form-control" name="preparation_time" value="10" min="1" max="60" required>
                                                <small class="form-text text-muted">Default preparation time for this station</small>
                                            </div>
                                            
                                            <button type="submit" class="btn btn-primary">
                                                <i class="feather feather-plus me-2"></i>Add Station
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-list me-2"></i>Existing Stations
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Description</th>
                                                        <th>Color</th>
                                                        <th>Prep Time</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php mysqli_data_seek($stations, 0); while ($station = $stations->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="color-preview" style="background-color: <?= htmlspecialchars($station['color']) ?>"></div>
                                                                <?= htmlspecialchars($station['name']) ?>
                                                            </div>
                                                        </td>
                                                        <td><?= htmlspecialchars($station['description']) ?></td>
                                                        <td>
                                                            <span class="badge" style="background-color: <?= htmlspecialchars($station['color']) ?>; color: white;">
                                                                <?= htmlspecialchars($station['color']) ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-info">
                                                                <?= isset($station['preparation_time']) ? $station['preparation_time'] : '10' ?> min
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php if ($station['is_active']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-secondary">Inactive</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-primary" 
                                                                    onclick="editStation(<?= $station['id'] ?>, '<?= htmlspecialchars($station['name']) ?>', '<?= htmlspecialchars($station['description']) ?>', '<?= htmlspecialchars($station['color']) ?>', <?= isset($station['preparation_time']) ? $station['preparation_time'] : '10' ?>, <?= $station['is_active'] ?>)"
                                                                    data-bs-toggle="tooltip" 
                                                                    title="Edit Station Settings">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <form method="POST" style="display: inline;">
                                                                <input type="hidden" name="action" value="delete_station">
                                                                <input type="hidden" name="station_id" value="<?= $station['id'] ?>">
                                                                <button type="submit" class="btn btn-sm btn-danger" 
                                                                        onclick="return confirm('Are you sure you want to delete this station?')"
                                                                        data-bs-toggle="tooltip" 
                                                                        title="Delete Station">
                                                                    <i class="fas fa-trash"></i>
                                                                </button>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Settings Tab -->
                    <div class="tab-pane fade" id="settings" role="tabpanel">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-toggle-right me-2"></i>General Settings
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="setting-item">
                                            <label class="form-label">Enable KDS</label>
                                            <form method="POST" class="d-flex align-items-center">
                                                <input type="hidden" name="action" value="update_setting">
                                                <input type="hidden" name="setting_key" value="enable_kds">
                                                <select name="setting_value" class="form-control me-2">
                                                    <option value="1" <?= ($kds_settings['enable_kds']['setting_value'] ?? '1') === '1' ? 'selected' : '' ?>>Enabled</option>
                                                    <option value="0" <?= ($kds_settings['enable_kds']['setting_value'] ?? '1') === '0' ? 'selected' : '' ?>>Disabled</option>
                                                </select>
                                                <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                            </form>
                                            <small class="text-muted">Enable or disable the KDS system</small>
                                        </div>

                                        <div class="setting-item">
                                            <label class="form-label">Auto Refresh Interval (seconds)</label>
                                            <form method="POST" class="d-flex align-items-center">
                                                <input type="hidden" name="action" value="update_setting">
                                                <input type="hidden" name="setting_key" value="auto_refresh_interval">
                                                <input type="number" class="form-control me-2" name="setting_value" 
                                                       value="<?= $kds_settings['auto_refresh_interval']['setting_value'] ?? '30' ?>" 
                                                       min="10" max="300">
                                                <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                            </form>
                                            <small class="text-muted">How often the KDS screen refreshes automatically</small>
                                        </div>

                                        <div class="setting-item">
                                            <label class="form-label">Sound Notifications</label>
                                            <form method="POST" class="d-flex align-items-center">
                                                <input type="hidden" name="action" value="update_setting">
                                                <input type="hidden" name="setting_key" value="sound_notifications">
                                                <select name="setting_value" class="form-control me-2">
                                                    <option value="1" <?= ($kds_settings['sound_notifications']['setting_value'] ?? '1') === '1' ? 'selected' : '' ?>>Enabled</option>
                                                    <option value="0" <?= ($kds_settings['sound_notifications']['setting_value'] ?? '1') === '0' ? 'selected' : '' ?>>Disabled</option>
                                                </select>
                                                <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                            </form>
                                            <small class="text-muted">Play sound when new orders arrive</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-clock me-2"></i>Time Settings
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="setting-item">
                                            <label class="form-label">Order Timeout (minutes)</label>
                                            <form method="POST" class="d-flex align-items-center">
                                                <input type="hidden" name="action" value="update_setting">
                                                <input type="hidden" name="setting_key" value="order_timeout_minutes">
                                                <input type="number" class="form-control me-2" name="setting_value" 
                                                       value="<?= $kds_settings['order_timeout_minutes']['setting_value'] ?? '45' ?>" 
                                                       min="15" max="120">
                                                <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                            </form>
                                            <small class="text-muted">Orders older than this will be highlighted</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Assignments Tab -->
                    <div class="tab-pane fade" id="assignments" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    <i class="feather feather-link me-2"></i>Item to Station Assignments
                                </h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Assign items to specific kitchen stations for better order management.</p>
                                
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <label for="category_filter" class="form-label">Filter by Category</label>
                                        <select class="form-control" id="category_filter">
                                            <option value="">All Categories</option>
                                            <?php mysqli_data_seek($categories, 0); while ($cat = $categories->fetch_assoc()): ?>
                                                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label for="station_filter" class="form-label">Filter by Station</label>
                                        <select class="form-control" id="station_filter">
                                            <option value="">All Stations</option>
                                            <?php mysqli_data_seek($stations, 0); while ($station = $stations->fetch_assoc()): ?>
                                                <option value="<?= $station['id'] ?>"><?= htmlspecialchars($station['name']) ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label for="search_items" class="form-label">Search Items</label>
                                        <input type="text" class="form-control" id="search_items" placeholder="Search items...">
                                    </div>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>Item</th>
                                                <th>Category</th>
                                                <th>Assigned Station</th>
                                                <th>Prep Time (min)</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="assignments_table">
                                            <!-- Items will be loaded here via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Cleanup Tab -->
                    <div class="tab-pane fade" id="cleanup" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    <i class="feather feather-trash-2 me-2"></i>KDS Record Cleanup
                                </h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Manage automatic cleanup of old KDS records to improve system performance and save storage space.</p>
                                
                                <!-- Current Statistics -->
                                <div class="row mb-4">
                                    <div class="col-md-8 mx-auto">
                                        <div class="card border-info">
                                            <div class="card-header bg-info text-white">
                                                <h6 class="mb-0">
                                                    <i class="feather feather-bar-chart-2 me-2"></i>Current Statistics
                                                </h6>
                                            </div>
                                            <div class="card-body" id="cleanup_stats">
                                                <div class="text-center">
                                                    <div class="spinner-border text-primary" role="status">
                                                        <span class="visually-hidden">Loading...</span>
                                                    </div>
                                                    <p class="mt-2">Loading statistics...</p>
                                                </div>
                                            </div>
                                            <div class="card-footer text-center">
                                                <button class="btn btn-outline-info btn-sm" onclick="loadCleanupStats()">
                                                    <i class="feather feather-refresh-cw me-2"></i>Refresh Stats
                                                </button>
                                                <small class="text-muted d-block mt-2">
                                                    Cleanup settings are managed in <strong>System Settings</strong>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Cleanup Actions -->
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <div class="card border-warning">
                                            <div class="card-header bg-warning text-dark">
                                                <h6 class="mb-0">
                                                    <i class="feather feather-zap me-2"></i>Cleanup Actions
                                                </h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="alert alert-info" role="alert">
                                                    <i class="feather feather-info me-2"></i>
                                                    <strong>Important:</strong> Cleanup will permanently delete old served/cancelled orders and their items. This action cannot be undone.
                                                </div>
                                                
                                                <div class="d-grid gap-2 d-md-flex justify-content-md-center">
                                                    <button class="btn btn-outline-primary" onclick="performDryRun()">
                                                        <i class="feather feather-eye me-2"></i>Preview Cleanup (Dry Run)
                                                    </button>
                                                    <button class="btn btn-warning" onclick="performCleanup()">
                                                        <i class="feather feather-trash-2 me-2"></i>Perform Cleanup Now
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Cleanup History -->
                                <div class="row">
                                    <div class="col-12">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="mb-0">
                                                    <i class="feather feather-clock me-2"></i>Cleanup History
                                                </h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="table-responsive">
                                                    <table class="table table-sm table-hover">
                                                        <thead>
                                                            <tr>
                                                                <th>Date</th>
                                                                <th>Retention Days</th>
                                                                <th>Orders Deleted</th>
                                                                <th>Items Deleted</th>
                                                                <th>Logs Deleted</th>
                                                                <th>Total</th>
                                                                <th>Time</th>
                                                                <th>Status</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody id="cleanup_history">
                                                            <!-- History will be loaded here -->
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Station Modal -->
<div class="modal fade" id="editStationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Station</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_station">
                    <input type="hidden" name="station_id" id="edit_station_id">
                    
                    <div class="form-group">
                        <label for="edit_station_name" class="form-label">Station Name</label>
                        <input type="text" class="form-control" id="edit_station_name" name="station_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_description" class="form-label">Description</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_color" class="form-label">Color</label>
                        <input type="color" class="form-control form-control-color" id="edit_color" name="color">
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_preparation_time" class="form-label">Preparation Time (minutes)</label>
                        <input type="number" class="form-control" id="edit_preparation_time" name="preparation_time" min="1" max="60" required>
                        <small class="form-text text-muted">Default preparation time for this station</small>
                    </div>
                    
                    <div class="form-group">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="edit_is_active" name="is_active">
                            <label class="form-check-label" for="edit_is_active">Active</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Station</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Load assignments when assignments tab is shown
    function loadAssignments() {
        const categoryFilter = document.getElementById('category_filter').value;
        const stationFilter = document.getElementById('station_filter').value;
        const searchFilter = document.getElementById('search_items').value;
        
        const params = new URLSearchParams();
        if (categoryFilter) params.append('category', categoryFilter);
        if (stationFilter) params.append('station', stationFilter);
        if (searchFilter) params.append('search', searchFilter);
        
        fetch(`ajax/kds_get_assignments.php?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayAssignments(data.assignments);
                } else {
                    console.error('Error loading assignments:', data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
    
    function displayAssignments(assignments) {
        const tbody = document.getElementById('assignments_table');
        let html = '';
        
        assignments.forEach(item => {
            html += `
                <tr>
                    <td>${item.name}</td>
                    <td>${item.category_name}</td>
                    <td>
                        <select class="form-control form-control-sm" onchange="updateAssignment(${item.id}, this.value)">
                            <option value="">No Station</option>
                            ${item.stations.map(station => 
                                `<option value="${station.id}" ${station.assigned ? 'selected' : ''}>${station.name}</option>`
                            ).join('')}
                        </select>
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               value="${item.prep_time || ''}" 
                               onchange="updatePrepTime(${item.id}, this.value)"
                               placeholder="Minutes">
                    </td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewItemDetails(${item.id})">
                            <i class="feather feather-eye"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
    }
    
    // Update item assignment
    function updateAssignment(itemId, stationId) {
        fetch('ajax/kds_update_assignment.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                item_id: itemId,
                station_id: stationId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Show success message
                console.log('Assignment updated successfully');
            } else {
                alert('Error updating assignment: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
    }
    
    // Update preparation time
    function updatePrepTime(itemId, prepTime) {
        fetch('ajax/kds_update_prep_time.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                item_id: itemId,
                prep_time: prepTime
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('Prep time updated successfully');
            } else {
                alert('Error updating prep time: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
    }
    
    // Edit station function
    function editStation(id, name, description, color, preparationTime, isActive) {
        document.getElementById('edit_station_id').value = id;
        document.getElementById('edit_station_name').value = name;
        document.getElementById('edit_description').value = description;
        document.getElementById('edit_color').value = color;
        document.getElementById('edit_preparation_time').value = preparationTime;
        document.getElementById('edit_is_active').checked = isActive;
        
        new bootstrap.Modal(document.getElementById('editStationModal')).show();
    }
    
    // Event listeners
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Load assignments when assignments tab is shown
        document.getElementById('assignments-tab').addEventListener('shown.bs.tab', function() {
            loadAssignments();
        });
        
        // Filter event listeners
        document.getElementById('category_filter').addEventListener('change', loadAssignments);
        document.getElementById('station_filter').addEventListener('change', loadAssignments);
        document.getElementById('search_items').addEventListener('input', loadAssignments);
        
        // Load cleanup data when cleanup tab is shown
        document.getElementById('cleanup-tab').addEventListener('shown.bs.tab', function() {
            loadCleanupStats();
            loadCleanupHistory();
        });
    });
    
    // KDS Cleanup Functions
    function loadCleanupStats() {
        fetch('ajax/kds_cleanup.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'get_stats' })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayCleanupStats(data.stats);
            } else {
                document.getElementById('cleanup_stats').innerHTML = 
                    '<div class="alert alert-danger">Error loading stats: ' + data.message + '</div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('cleanup_stats').innerHTML = 
                '<div class="alert alert-danger">Network error occurred</div>';
        });
    }
    
    function displayCleanupStats(stats) {
        const html = `
            <div class="row text-center">
                <div class="col-6">
                    <div class="border-end">
                        <h4 class="text-primary mb-1">${stats.current_orders}</h4>
                        <small class="text-muted">Current Orders</small>
                    </div>
                </div>
                <div class="col-6">
                    <h4 class="text-info mb-1">${stats.current_order_items}</h4>
                    <small class="text-muted">Current Items</small>
                </div>
            </div>
            <hr>
            <div class="row text-center">
                <div class="col-12 mb-2">
                    <h5 class="text-warning mb-1">${stats.old_orders + stats.old_activity_logs}</h5>
                    <small class="text-muted">Records to be cleaned (${stats.retention_days} days)</small>
                </div>
            </div>
            <div class="small">
                <div class="d-flex justify-content-between">
                    <span>Auto Cleanup:</span>
                    <span class="${stats.auto_cleanup_enabled ? 'text-success' : 'text-danger'}">
                        ${stats.auto_cleanup_enabled ? 'Enabled' : 'Disabled'}
                    </span>
                </div>
                <div class="d-flex justify-content-between">
                    <span>Last Cleanup:</span>
                    <span class="text-muted">
                        ${stats.last_cleanup_date ? new Date(stats.last_cleanup_date).toLocaleString() : 'Never'}
                    </span>
                </div>
            </div>
        `;
        
        document.getElementById('cleanup_stats').innerHTML = html;
    }
    

    
    function performDryRun() {
        if (!confirm('This will show what records would be deleted without actually deleting them. Continue?')) {
            return;
        }
        
        const btn = event.target;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Running...';
        
        fetch('ajax/kds_cleanup.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'dry_run'
            })
        })
        .then(response => response.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="feather feather-eye me-2"></i>Preview Cleanup (Dry Run)';
            
            if (data.success) {
                const message = `Dry Run Results:
                
Retention Period: ${data.retention_days} days
Cutoff Date: ${data.cutoff_date}

Records that would be deleted:
• Orders: ${data.orders_deleted}
• Order Items: ${data.order_items_deleted}
• Activity Logs: ${data.activity_logs_deleted}
• Total: ${data.total_records_deleted}

Execution Time: ${data.execution_time_ms}ms`;
                
                alert(message);
                loadCleanupStats();
            } else {
                alert('Dry run failed: ' + data.message);
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = '<i class="feather feather-eye me-2"></i>Preview Cleanup (Dry Run)';
            console.error('Error:', error);
            alert('Network error occurred');
        });
    }
    
    function performCleanup() {
        const confirmMessage = `⚠️ WARNING: This will permanently delete old KDS records based on your current settings.
        
This action cannot be undone!

Are you sure you want to continue?`;
        
        if (!confirm(confirmMessage)) {
            return;
        }
        
        const btn = event.target;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Cleaning...';
        
        fetch('ajax/kds_cleanup.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'cleanup'
            })
        })
        .then(response => response.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="feather feather-trash-2 me-2"></i>Perform Cleanup Now';
            
            if (data.success) {
                const message = `✅ Cleanup Completed Successfully!
                
• Orders deleted: ${data.orders_deleted}
• Order Items deleted: ${data.order_items_deleted}
• Activity Logs deleted: ${data.activity_logs_deleted}
• Total records deleted: ${data.total_records_deleted}
• Execution time: ${data.execution_time_ms}ms`;
                
                alert(message);
                loadCleanupStats();
                loadCleanupHistory();
            } else {
                alert('Cleanup failed: ' + data.message);
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = '<i class="feather feather-trash-2 me-2"></i>Perform Cleanup Now';
            console.error('Error:', error);
            alert('Network error occurred');
        });
    }
    
    function loadCleanupHistory() {
        fetch('ajax/kds_cleanup.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'get_cleanup_history', limit: 10 })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayCleanupHistory(data.history);
            } else {
                document.getElementById('cleanup_history').innerHTML = 
                    '<tr><td colspan="8" class="text-center text-danger">Error loading history</td></tr>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('cleanup_history').innerHTML = 
                '<tr><td colspan="8" class="text-center text-danger">Network error</td></tr>';
        });
    }
    
    function displayCleanupHistory(history) {
        if (history.length === 0) {
            document.getElementById('cleanup_history').innerHTML = 
                '<tr><td colspan="8" class="text-center text-muted">No cleanup history found</td></tr>';
            return;
        }
        
        const html = history.map(entry => {
            const date = new Date(entry.cleanup_date).toLocaleString();
            const statusClass = entry.status === 'success' ? 'text-success' : 
                               entry.status === 'failed' ? 'text-danger' : 'text-warning';
            
            return `
                <tr>
                    <td>${date}</td>
                    <td>${entry.retention_days}</td>
                    <td>${entry.orders_deleted}</td>
                    <td>${entry.order_items_deleted}</td>
                    <td>${entry.activity_logs_deleted}</td>
                    <td><strong>${entry.total_records_deleted}</strong></td>
                    <td>${entry.execution_time_ms}ms</td>
                    <td><span class="${statusClass}">${entry.status}</span></td>
                </tr>
            `;
        }).join('');
        
        document.getElementById('cleanup_history').innerHTML = html;
    }
</script>


