<?php
session_start();
require_once 'config/db_config.php';

// Validate session
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'branch' || !isset($_SESSION['branch_id'])) {
    header("Location: login.php");
    exit();
}

$branch_id = $_SESSION['branch_id'];
$errors = [];
$success = '';
$tables = [];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_table'])) {
        // Add new table
        $table_number = trim($_POST['table_number']);
        $table_capacity = (int)$_POST['table_capacity'];
        $status = $_POST['status'];

        // Validation
        if (empty($table_number)) {
            $errors[] = "Table number is required";
        } elseif (!preg_match('/^[A-Za-z0-9\- ]+$/', $table_number)) {
            $errors[] = "Table number can only contain letters, numbers, spaces, and hyphens";
        }

        if ($table_capacity < 1 || $table_capacity > 20) {
            $errors[] = "Table capacity must be between 1 and 20";
        }

        // Check for duplicate table number
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("SELECT table_id FROM branch_tables WHERE branch_id = :branch_id AND table_number = :table_number");
                $stmt->execute([':branch_id' => $branch_id, ':table_number' => $table_number]);
                if ($stmt->fetch()) {
                    $errors[] = "Table number '$table_number' already exists in this branch";
                }
            } catch (PDOException $e) {
                $errors[] = "Error checking table existence: " . $e->getMessage();
            }
        }

        // Insert new table
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO branch_tables (branch_id, table_number, table_capacity, status) 
                    VALUES (:branch_id, :table_number, :table_capacity, :status)
                ");
                $stmt->execute([
                    ':branch_id' => $branch_id,
                    ':table_number' => $table_number,
                    ':table_capacity' => $table_capacity,
                    ':status' => $status
                ]);
                $success = "Table '$table_number' added successfully!";
            } catch (PDOException $e) {
                $errors[] = "Error adding table: " . $e->getMessage();
            }
        }
    }
    elseif (isset($_POST['update_table'])) {
        // Update table
        $table_id = (int)$_POST['table_id'];
        $table_number = trim($_POST['table_number']);
        $table_capacity = (int)$_POST['table_capacity'];
        $status = $_POST['status'];

        // Validation
        if (empty($table_number)) {
            $errors[] = "Table number is required";
        }

        if ($table_capacity < 1 || $table_capacity > 20) {
            $errors[] = "Table capacity must be between 1 and 20";
        }

        // Check for duplicate table number (excluding current table)
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("
                    SELECT table_id FROM branch_tables 
                    WHERE branch_id = :branch_id AND table_number = :table_number AND table_id != :table_id
                ");
                $stmt->execute([
                    ':branch_id' => $branch_id,
                    ':table_number' => $table_number,
                    ':table_id' => $table_id
                ]);
                if ($stmt->fetch()) {
                    $errors[] = "Table number '$table_number' already exists in this branch";
                }
            } catch (PDOException $e) {
                $errors[] = "Error checking table existence: " . $e->getMessage();
            }
        }

        // Update table
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("
                    UPDATE branch_tables 
                    SET table_number = :table_number, table_capacity = :table_capacity, status = :status 
                    WHERE table_id = :table_id AND branch_id = :branch_id
                ");
                $stmt->execute([
                    ':table_number' => $table_number,
                    ':table_capacity' => $table_capacity,
                    ':status' => $status,
                    ':table_id' => $table_id,
                    ':branch_id' => $branch_id
                ]);
                $success = "Table '$table_number' updated successfully!";
            } catch (PDOException $e) {
                $errors[] = "Error updating table: " . $e->getMessage();
            }
        }
    }
    elseif (isset($_POST['delete_table'])) {
        // Delete table
        $table_id = (int)$_POST['table_id'];
        
        // Check if table has active orders
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as order_count 
                FROM orders 
                WHERE branch_id = :branch_id AND table_number IN (
                    SELECT table_number FROM branch_tables WHERE table_id = :table_id
                ) AND status IN ('pending', 'processing')
            ");
            $stmt->execute([':branch_id' => $branch_id, ':table_id' => $table_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result['order_count'] > 0) {
                $errors[] = "Cannot delete table with active orders. Please complete or cancel orders first.";
            } else {
                // Delete table
                $stmt = $pdo->prepare("DELETE FROM branch_tables WHERE table_id = :table_id AND branch_id = :branch_id");
                $stmt->execute([':table_id' => $table_id, ':branch_id' => $branch_id]);
                
                if ($stmt->rowCount() > 0) {
                    $success = "Table deleted successfully!";
                } else {
                    $errors[] = "Table not found or you don't have permission to delete it";
                }
            }
        } catch (PDOException $e) {
            $errors[] = "Error deleting table: " . $e->getMessage();
        }
    }
}

// Fetch all tables for this branch
try {
    $stmt = $pdo->prepare("
        SELECT table_id, table_number, table_capacity, status, created_at 
        FROM branch_tables 
        WHERE branch_id = :branch_id 
        ORDER BY 
            CASE 
                WHEN table_number REGEXP '^[0-9]+$' THEN CAST(table_number AS UNSIGNED)
                ELSE 999999
            END,
            table_number
    ");
    $stmt->execute([':branch_id' => $branch_id]);
    $tables = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $errors[] = "Error fetching tables: " . $e->getMessage();
}

include './partials/layouts/layoutTop.php';
?>

<style>
    .table-card {
        transition: all 0.3s ease;
        border: 1px solid #e9ecef;
    }
    .table-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    .status-available { border-left: 4px solid #28a745; }
    .status-occupied { border-left: 4px solid #dc3545; }
    .status-reserved { border-left: 4px solid #ffc107; }
    .status-maintenance { border-left: 4px solid #6c757d; }
    .table-badge {
        font-size: 0.75rem;
        padding: 0.35em 0.65em;
    }
    .capacity-badge {
        background: #e9ecef;
        color: #495057;
    }
    .table-actions .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    .table-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1.5rem;
    }
    @media (max-width: 768px) {
        .table-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="dashboard-main-body">
    <!-- Breadcrumb -->
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-16">
        <h6 class="fw-semibold mb-0 text-md">Table Management</h6>
        <ul class="d-flex align-items-center gap-1">
            <li class="fw-medium text-sm">
                <a href="index.php" class="d-flex align-items-center gap-1 hover-text-primary">
                    <i class="fas fa-home fa-icon"></i> Dashboard
                </a>
            </li>
            <li>-</li>
            <li class="fw-medium text-sm">Tables</li>
        </ul>
    </div>

    <!-- Alerts -->
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <ul class="mb-0 text-sm">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
            <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (!empty($success)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <span class="text-sm"><?php echo htmlspecialchars($success); ?></span>
            <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Add Table Form -->
        <div class="col-lg-4 mb-16">
            <div class="card">
                <div class="card-header">
                    <h5 class="section-title card-title mb-0 text-md">
                        <i class="fas fa-plus-circle me-2"></i>Add New Table
                    </h5>
                </div>
                <div class="card-body">
                    <form method="POST" id="addTableForm">
                        <div class="mb-3">
                            <label for="table_number" class="form-label fw-medium text-sm">Table Number *</label>
                            <input type="text" class="form-control form-control-sm bg-base" 
                                   id="table_number" name="table_number" 
                                   placeholder="e.g., T1, Table 2, A-1" 
                                   value="<?php echo isset($_POST['table_number']) ? htmlspecialchars($_POST['table_number']) : ''; ?>" 
                                   required>
                            <div class="form-text">Unique identifier for the table</div>
                        </div>

                        <div class="mb-3">
                            <label for="table_capacity" class="form-label fw-medium text-sm">Capacity *</label>
                            <input type="number" class="form-control form-control-sm bg-base" 
                                   id="table_capacity" name="table_capacity" 
                                   min="1" max="20" value="4" required>
                            <div class="form-text">Number of people the table can accommodate (1-20)</div>
                        </div>

                        <div class="mb-3">
                            <label for="status" class="form-label fw-medium text-sm">Status *</label>
                            <select class="form-select form-select-sm bg-base" id="status" name="status" required>
                                <option value="available" selected>Available</option>
                                <option value="occupied">Occupied</option>
                                <option value="reserved">Reserved</option>
                                <option value="maintenance">Maintenance</option>
                            </select>
                        </div>

                        <button type="submit" name="add_table" class="btn btn-primary btn-sm w-100">
                            <i class="fas fa-plus me-2"></i>Add Table
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Tables List -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex flex-wrap align-items-center justify-content-between">
                        <h5 class="section-title card-title mb-0 text-md">
                            <i class="fas fa-list me-2"></i>All Tables (<?php echo count($tables); ?>)
                        </h5>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleView()">
                                <i class="fas fa-th me-1"></i> Toggle View
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($tables)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-table text-3xl text-secondary mb-3 d-block"></i>
                            <h6 class="text-md text-secondary">No Tables Found</h6>
                            <p class="text-sm text-muted">Start by adding your first table using the form on the left.</p>
                        </div>
                    <?php else: ?>
                        <!-- Grid View -->
                        <div class="table-grid" id="gridView">
                            <?php foreach ($tables as $table): 
                                $status_class = 'status-' . $table['status'];
                                $status_badge = [
                                    'available' => ['class' => 'bg-success', 'text' => 'Available'],
                                    'occupied' => ['class' => 'bg-danger', 'text' => 'Occupied'],
                                    'reserved' => ['class' => 'bg-warning text-dark', 'text' => 'Reserved'],
                                    'maintenance' => ['class' => 'bg-secondary', 'text' => 'Maintenance']
                                ];
                            ?>
                                <div class="card table-card <?php echo $status_class; ?>">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <h6 class="card-title mb-0 text-sm fw-bold">
                                                <i class="fas fa-table me-2"></i><?php echo htmlspecialchars($table['table_number']); ?>
                                            </h6>
                                            <span class="badge table-badge <?php echo $status_badge[$table['status']]['class']; ?>">
                                                <?php echo $status_badge[$table['status']]['text']; ?>
                                            </span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <span class="text-sm">
                                                <i class="fas fa-users me-1"></i>Capacity: 
                                                <strong><?php echo $table['table_capacity']; ?></strong>
                                            </span>
                                            <span class="badge capacity-badge table-badge">
                                                <?php echo $table['table_capacity']; ?> seats
                                            </span>
                                        </div>

                                        <div class="text-sm text-muted mb-3">
                                            <i class="fas fa-calendar me-1"></i>
                                            Added: <?php echo date('M j, Y', strtotime($table['created_at'])); ?>
                                        </div>

                                        <div class="table-actions d-flex gap-2">
                                            <button type="button" class="btn btn-outline-primary btn-sm flex-fill" 
                                                    onclick="editTable(<?php echo $table['table_id']; ?>)"
                                                    data-bs-toggle="tooltip" title="Edit Table">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-danger btn-sm" 
                                                    onclick="confirmDelete(<?php echo $table['table_id']; ?>, '<?php echo htmlspecialchars($table['table_number']); ?>')"
                                                    data-bs-toggle="tooltip" title="Delete Table">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Table View (Hidden by default) -->
                        <div class="table-responsive d-none" id="tableView">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Table Number</th>
                                        <th>Capacity</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($tables as $table): 
                                        $status_badge = [
                                            'available' => ['class' => 'bg-success', 'text' => 'Available'],
                                            'occupied' => ['class' => 'bg-danger', 'text' => 'Occupied'],
                                            'reserved' => ['class' => 'bg-warning text-dark', 'text' => 'Reserved'],
                                            'maintenance' => ['class' => 'bg-secondary', 'text' => 'Maintenance']
                                        ];
                                    ?>
                                        <tr>
                                            <td>
                                                <strong class="text-sm">
                                                    <i class="fas fa-table me-2"></i><?php echo htmlspecialchars($table['table_number']); ?>
                                                </strong>
                                            </td>
                                            <td>
                                                <span class="badge capacity-badge">
                                                    <?php echo $table['table_capacity']; ?> seats
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge table-badge <?php echo $status_badge[$table['status']]['class']; ?>">
                                                    <?php echo $status_badge[$table['status']]['text']; ?>
                                                </span>
                                            </td>
                                            <td class="text-sm">
                                                <?php echo date('M j, Y', strtotime($table['created_at'])); ?>
                                            </td>
                                            <td>
                                                <div class="d-flex gap-1">
                                                    <button type="button" class="btn btn-outline-primary btn-sm" 
                                                            onclick="editTable(<?php echo $table['table_id']; ?>)"
                                                            data-bs-toggle="tooltip" title="Edit Table">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-danger btn-sm" 
                                                            onclick="confirmDelete(<?php echo $table['table_id']; ?>, '<?php echo htmlspecialchars($table['table_number']); ?>')"
                                                            data-bs-toggle="tooltip" title="Delete Table">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Table Modal -->
<div class="modal fade" id="editTableModal" tabindex="-1" aria-labelledby="editTableModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-md" id="editTableModalLabel">
                    <i class="fas fa-edit me-2"></i>Edit Table
                </h5>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="editTableForm">
                <div class="modal-body">
                    <input type="hidden" name="table_id" id="edit_table_id">
                    
                    <div class="mb-3">
                        <label for="edit_table_number" class="form-label fw-medium text-sm">Table Number *</label>
                        <input type="text" class="form-control form-control-sm bg-base" 
                               id="edit_table_number" name="table_number" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_table_capacity" class="form-label fw-medium text-sm">Capacity *</label>
                        <input type="number" class="form-control form-control-sm bg-base" 
                               id="edit_table_capacity" name="table_capacity" 
                               min="1" max="20" required>
                    </div>

                    <div class="mb-3">
                        <label for="edit_status" class="form-label fw-medium text-sm">Status *</label>
                        <select class="form-select form-select-sm bg-base" id="edit_status" name="status" required>
                            <option value="available">Available</option>
                            <option value="occupied">Occupied</option>
                            <option value="reserved">Reserved</option>
                            <option value="maintenance">Maintenance</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="submit" name="update_table" class="btn btn-primary btn-sm">
                        <i class="fas fa-save me-2"></i>Update Table
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteTableModal" tabindex="-1" aria-labelledby="deleteTableModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-md text-danger" id="deleteTableModalLabel">
                    <i class="fas fa-exclamation-triangle me-2"></i>Confirm Delete
                </h5>
                <button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="deleteTableForm">
                <div class="modal-body">
                    <input type="hidden" name="table_id" id="delete_table_id">
                    <p class="text-sm mb-0">
                        Are you sure you want to delete table "<strong id="delete_table_name"></strong>"?
                        This action cannot be undone.
                    </p>
                    <div class="alert alert-warning mt-2 p-2 text-sm">
                        <i class="fas fa-exclamation-circle me-1"></i>
                        Cannot delete tables with active orders.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button type="submit" name="delete_table" class="btn btn-danger btn-sm">
                        <i class="fas fa-trash me-2"></i>Delete Table
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php'; ?>

<script>
    let currentView = 'grid'; // 'grid' or 'table'

    function toggleView() {
        const gridView = document.getElementById('gridView');
        const tableView = document.getElementById('tableView');
        const toggleBtn = event.target;
        
        if (currentView === 'grid') {
            gridView.classList.add('d-none');
            tableView.classList.remove('d-none');
            toggleBtn.innerHTML = '<i class="fas fa-th-large me-1"></i> Grid View';
            currentView = 'table';
        } else {
            tableView.classList.add('d-none');
            gridView.classList.remove('d-none');
            toggleBtn.innerHTML = '<i class="fas fa-th me-1"></i> Table View';
            currentView = 'grid';
        }
    }

    function editTable(tableId) {
        // Fetch table details via AJAX
        fetch(`get_table_details.php?table_id=${tableId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('edit_table_id').value = data.table.table_id;
                    document.getElementById('edit_table_number').value = data.table.table_number;
                    document.getElementById('edit_table_capacity').value = data.table.table_capacity;
                    document.getElementById('edit_status').value = data.table.status;
                    
                    const modal = new bootstrap.Modal(document.getElementById('editTableModal'));
                    modal.show();
                } else {
                    alert('Error loading table details');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading table details');
            });
    }

    function confirmDelete(tableId, tableName) {
        document.getElementById('delete_table_id').value = tableId;
        document.getElementById('delete_table_name').textContent = tableName;
        
        const modal = new bootstrap.Modal(document.getElementById('deleteTableModal'));
        modal.show();
    }

    // Initialize tooltips
    document.addEventListener('DOMContentLoaded', function() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });
</script>