<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Restaurant Tables';

if (!function_exists('h')) {
    function h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('rt_flash')) {
    function rt_flash($t, $m): void
    {
        $_SESSION['rt_flash'][] = ['type' => $t, 'message' => $m];
    }

    function rt_get_flash(): array
    {
        $x = $_SESSION['rt_flash'] ?? [];
        unset($_SESSION['rt_flash']);
        return $x;
    }
}

if (!function_exists('rt_column_exists')) {
    function rt_column_exists(PDO $pdo, string $table, string $column): bool
    {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([
            ':table_name' => $table,
            ':column_name' => $column,
        ]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_areas (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        area_name VARCHAR(120) NOT NULL,
        sort_order INT NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_tables (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        area_id INT UNSIGNED NULL,
        table_no VARCHAR(40) NOT NULL,
        table_name VARCHAR(120) NULL,
        seats INT UNSIGNED NOT NULL DEFAULT 2,
        pos_x INT NOT NULL DEFAULT 0,
        pos_y INT NOT NULL DEFAULT 0,
        shape ENUM('round','square','rect') NOT NULL DEFAULT 'round',
        orientation ENUM('horizontal','vertical') NOT NULL DEFAULT 'horizontal',
        status ENUM('available','occupied','reserved','dirty','blocked') NOT NULL DEFAULT 'available',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_rest_table_area(area_id),
        INDEX idx_rest_table_status(status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    if (!rt_column_exists($pdo, 'restaurant_tables', 'orientation')) {
        $pdo->exec("ALTER TABLE restaurant_tables ADD COLUMN orientation ENUM('horizontal','vertical') NOT NULL DEFAULT 'horizontal' AFTER shape");
    }
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $duplicateField = '';

    try {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }

        $a = $_POST['action'] ?? '';

        if ($a === 'save_area') {
            $id = (int)($_POST['id'] ?? 0);
            $n = trim((string)($_POST['area_name'] ?? ''));

            if ($n === '') {
                throw new RuntimeException('Area name required.');
            }

            if ($id > 0) {
                $pdo->prepare("UPDATE restaurant_areas SET area_name=:n, sort_order=:s, is_active=:ia WHERE id=:id")
                    ->execute([
                        ':n' => $n,
                        ':s' => (int)($_POST['sort_order'] ?? 1),
                        ':ia' => (int)($_POST['is_active'] ?? 1),
                        ':id' => $id,
                    ]);
            } else {
                $pdo->prepare("INSERT INTO restaurant_areas(area_name, sort_order, is_active) VALUES(:n, :s, 1)")
                    ->execute([
                        ':n' => $n,
                        ':s' => (int)($_POST['sort_order'] ?? 1),
                    ]);
            }

            rt_flash('success', 'Area saved.');
            header('Location: restaurant_tables.php');
            exit;
        }

        if ($a === 'save_table') {
            $id = (int)($_POST['id'] ?? 0);
            $no = trim((string)($_POST['table_no'] ?? ''));
            $shape = strtolower(trim((string)($_POST['shape'] ?? 'round')));
            $orientation = strtolower(trim((string)($_POST['orientation'] ?? 'horizontal')));

            if ($no === '') {
                $duplicateField = 'table_no';
                throw new RuntimeException('Table number required.');
            }
            if (!in_array($shape, ['round', 'square', 'rect'], true)) {
                $shape = 'round';
            }
            if (!in_array($orientation, ['horizontal', 'vertical'], true)) {
                $orientation = 'horizontal';
            }

            $areaId = (int)($_POST['area_id'] ?? 0);
            $areaId = $areaId > 0 ? $areaId : null;
            $tableName = trim((string)($_POST['table_name'] ?? ''));
            $tableName = $tableName !== '' ? $tableName : null;

            $stmtDupNo = $pdo->prepare("
                SELECT COUNT(*)
                FROM restaurant_tables
                WHERE table_no = :table_no
                  AND COALESCE(area_id, 0) = COALESCE(:area_id, 0)
                  AND id <> :current_id
            ");
            $stmtDupNo->execute([
                ':table_no' => $no,
                ':area_id' => $areaId,
                ':current_id' => $id,
            ]);

            if ((int)$stmtDupNo->fetchColumn() > 0) {
                $duplicateField = 'table_no';
                throw new RuntimeException('Duplicate table number in this area. Please change the highlighted Table No.');
            }

            if ($tableName !== null) {
                $stmtDupName = $pdo->prepare("
                    SELECT COUNT(*)
                    FROM restaurant_tables
                    WHERE table_name = :table_name
                      AND COALESCE(area_id, 0) = COALESCE(:area_id, 0)
                      AND id <> :current_id
                ");
                $stmtDupName->execute([
                    ':table_name' => $tableName,
                    ':area_id' => $areaId,
                    ':current_id' => $id,
                ]);

                if ((int)$stmtDupName->fetchColumn() > 0) {
                    $duplicateField = 'table_name';
                    throw new RuntimeException('Duplicate table name in this area. Please change the highlighted Table Name.');
                }
            }

            $p = [
                ':area' => $areaId,
                ':no' => $no,
                ':name' => $tableName,
                ':seats' => max(1, (int)($_POST['seats'] ?? 2)),
                ':x' => (int)($_POST['pos_x'] ?? 0),
                ':y' => (int)($_POST['pos_y'] ?? 0),
                ':shape' => $shape,
                ':orientation' => $orientation,
                ':status' => $_POST['status'] ?? 'available',
                ':active' => (int)($_POST['is_active'] ?? 1),
            ];

            if ($id > 0) {
                $p[':id'] = $id;
                $pdo->prepare("
                    UPDATE restaurant_tables
                    SET area_id=:area,
                        table_no=:no,
                        table_name=:name,
                        seats=:seats,
                        pos_x=:x,
                        pos_y=:y,
                        shape=:shape,
                        orientation=:orientation,
                        status=:status,
                        is_active=:active
                    WHERE id=:id
                ")->execute($p);
            } else {
                $pdo->prepare("
                    INSERT INTO restaurant_tables
                    (area_id, table_no, table_name, seats, pos_x, pos_y, shape, orientation, status, is_active)
                    VALUES
                    (:area, :no, :name, :seats, :x, :y, :shape, :orientation, :status, :active)
                ")->execute($p);
            }

            unset($_SESSION['rt_table_form_data'], $_SESSION['rt_table_form_error'], $_SESSION['rt_table_form_error_field']);
            rt_flash('success', 'Table saved.');
            header('Location: restaurant_tables.php');
            exit;
        }

        header('Location: restaurant_tables.php');
        exit;
    } catch (Throwable $e) {
        if (($_POST['action'] ?? '') === 'save_table') {
            $_SESSION['rt_table_form_data'] = $_POST;
            $_SESSION['rt_table_form_error'] = $e->getMessage();
            $_SESSION['rt_table_form_error_field'] = $duplicateField;
        } else {
            rt_flash('danger', $e->getMessage());
        }
        header('Location: restaurant_tables.php#tableFormCard');
        exit;
    }
}

$formData = $_SESSION['rt_table_form_data'] ?? [];
$formError = $_SESSION['rt_table_form_error'] ?? '';
$formErrorField = $_SESSION['rt_table_form_error_field'] ?? '';
unset($_SESSION['rt_table_form_data'], $_SESSION['rt_table_form_error'], $_SESSION['rt_table_form_error_field']);

$flashes = rt_get_flash();
$areas = [];
$tables = [];

try {
    $areas = $pdo->query("SELECT * FROM restaurant_areas ORDER BY sort_order, area_name")->fetchAll(PDO::FETCH_ASSOC);
    $tables = $pdo->query("
        SELECT t.*, a.area_name
        FROM restaurant_tables t
        LEFT JOIN restaurant_areas a ON a.id = t.area_id
        ORDER BY a.sort_order, t.table_no
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

function rt_form_value(array $formData, string $key, $default = ''): string
{
    return (string)($formData[$key] ?? $default);
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band compact-restaurant-hero">
    <div class="row align-items-center">
        <div class="col">
            <div class="page-eyebrow text-white-50"><i class="bi bi-grid-3x3-gap"></i> Restaurant Setup</div>
            <div class="hero-title mt-1">Tables &amp; Areas</div>
        </div>
        <div class="col-auto">
            <a href="restaurant_planner.php" class="btn btn-light btn-sm">Planner</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $f): ?>
    <div class="alert alert-<?php echo h($f['type']); ?>"><?php echo h($f['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <?php foreach ($errors as $err): ?>
            <div><?php echo h($err); ?></div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-lg-4">
        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Area</h5></div>
            <div class="card-body">
                <form method="post" id="areaForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_area">
                    <input type="hidden" name="id" id="area_id">

                    <label class="form-label">Area Name</label>
                    <input name="area_name" id="area_name" class="form-control" required>

                    <div class="row g-2 mt-1">
                        <div class="col">
                            <label class="form-label">Sort</label>
                            <input type="number" name="sort_order" id="area_sort" value="1" class="form-control">
                        </div>
                        <div class="col">
                            <label class="form-label">Active</label>
                            <select name="is_active" id="area_active" class="form-select">
                                <option value="1">Yes</option>
                                <option value="0">No</option>
                            </select>
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 mt-3">Save Area</button>
                </form>

                <hr>

                <?php foreach ($areas as $a): ?>
                    <button class="btn btn-sm btn-light border mb-1 edit-area" data-json='<?php echo h(json_encode($a)); ?>'>
                        <?php echo h($a['area_name']); ?>
                    </button>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card panel-card" id="tableFormCard">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Table</h5>
                <span class="badge text-bg-light border">Rectangles can be horizontal or vertical</span>
            </div>
            <div class="card-body">
                <?php if ($formError): ?>
                    <div class="alert alert-danger duplicate-alert">
                        <strong>Cannot save table.</strong><br>
                        <?php echo h($formError); ?>
                    </div>
                <?php endif; ?>

                <form method="post" class="row g-2" id="tableForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_table">
                    <input type="hidden" name="id" id="table_id" value="<?php echo h(rt_form_value($formData, 'id', '')); ?>">

                    <div class="col-md-3">
                        <label class="form-label">Area</label>
                        <select name="area_id" id="table_area" class="form-select">
                            <option value="">None</option>
                            <?php foreach ($areas as $a): ?>
                                <option value="<?php echo (int)$a['id']; ?>" <?php echo rt_form_value($formData, 'area_id') == (string)$a['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($a['area_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Table No</label>
                        <input name="table_no" id="table_no" value="<?php echo h(rt_form_value($formData, 'table_no')); ?>" class="form-control <?php echo $formErrorField === 'table_no' ? 'is-duplicate-field' : ''; ?>" required>
                        <div class="form-text">Unique per area.</div>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Name</label>
                        <input name="table_name" id="table_name" value="<?php echo h(rt_form_value($formData, 'table_name')); ?>" class="form-control <?php echo $formErrorField === 'table_name' ? 'is-duplicate-field' : ''; ?>">
                        <div class="form-text">Must be unique within selected area.</div>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Seats</label>
                        <input type="number" name="seats" id="table_seats" value="<?php echo h(rt_form_value($formData, 'seats', '2')); ?>" class="form-control">
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Shape</label>
                        <?php $shapeVal = rt_form_value($formData, 'shape', 'round'); ?>
                        <select name="shape" id="table_shape" class="form-select">
                            <option value="round" <?php echo $shapeVal === 'round' ? 'selected' : ''; ?>>round</option>
                            <option value="square" <?php echo $shapeVal === 'square' ? 'selected' : ''; ?>>square</option>
                            <option value="rect" <?php echo $shapeVal === 'rect' ? 'selected' : ''; ?>>rect</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Orientation</label>
                        <?php $orientationVal = rt_form_value($formData, 'orientation', 'horizontal'); ?>
                        <select name="orientation" id="table_orientation" class="form-select">
                            <option value="horizontal" <?php echo $orientationVal === 'horizontal' ? 'selected' : ''; ?>>Horizontal / long side right</option>
                            <option value="vertical" <?php echo $orientationVal === 'vertical' ? 'selected' : ''; ?>>Vertical / long side down</option>
                        </select>
                        <div class="form-text">Use vertical for long tables going down.</div>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">X</label>
                        <input type="number" name="pos_x" id="table_x" value="<?php echo h(rt_form_value($formData, 'pos_x', '0')); ?>" class="form-control">
                        <div class="form-text">Left / right</div>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Y</label>
                        <input type="number" name="pos_y" id="table_y" value="<?php echo h(rt_form_value($formData, 'pos_y', '0')); ?>" class="form-control">
                        <div class="form-text">Top / bottom</div>
                    </div>

                    <div class="col-md-12">
                        <div class="layout-help-note">
                            <div><strong><i class="bi bi-info-circle me-1"></i>Table Layout Tip</strong></div>
                            <div>
                                X moves a table left/right. Y moves it up/down. To avoid overlap, leave about
                                <strong>150px</strong> between X positions and <strong>120px</strong> between Y positions.
                                Rectangular tables can now be <strong>horizontal</strong> or <strong>vertical</strong>.
                                Table No and Table Name cannot be duplicated within the same area.
                            </div>
                            <div class="layout-grid-example">
                                <span>T1: X=30, Y=50</span>
                                <span>T2: X=180, Y=50</span>
                                <span>T3: X=330, Y=50</span>
                                <span>T4: X=30, Y=170</span>
                                <span>Vertical Rect: Shape=rect, Orientation=vertical</span>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <?php $statusVal = rt_form_value($formData, 'status', 'available'); ?>
                        <select name="status" id="table_status" class="form-select">
                            <?php foreach (['available', 'occupied', 'reserved', 'dirty', 'blocked'] as $st): ?>
                                <option value="<?php echo h($st); ?>" <?php echo $statusVal === $st ? 'selected' : ''; ?>><?php echo h($st); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">Active</label>
                        <?php $activeVal = rt_form_value($formData, 'is_active', '1'); ?>
                        <select name="is_active" id="table_active" class="form-select">
                            <option value="1" <?php echo $activeVal === '1' ? 'selected' : ''; ?>>Yes</option>
                            <option value="0" <?php echo $activeVal === '0' ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>

                    <div class="col-md-3 d-flex align-items-end">
                        <button class="btn btn-primary w-100">Save Table</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card mt-3">
            <div class="table-responsive">
                <table class="table table-modern mb-0">
                    <thead>
                    <tr>
                        <th>Area</th>
                        <th>Table</th>
                        <th>Seats</th>
                        <th>Shape</th>
                        <th>Orientation</th>
                        <th>Status</th>
                        <th>Position</th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($tables as $t): ?>
                        <tr>
                            <td><?php echo h($t['area_name']); ?></td>
                            <td>
                                <strong><?php echo h($t['table_no']); ?></strong>
                                <div class="small text-muted"><?php echo h($t['table_name']); ?></div>
                            </td>
                            <td><?php echo (int)$t['seats']; ?></td>
                            <td><span class="badge text-bg-light border"><?php echo h($t['shape']); ?></span></td>
                            <td>
                                <?php $orientation = $t['orientation'] ?? 'horizontal'; ?>
                                <span class="badge <?php echo $orientation === 'vertical' ? 'text-bg-info' : 'text-bg-secondary'; ?>">
                                    <?php echo h($orientation); ?>
                                </span>
                            </td>
                            <td><span class="badge text-bg-light border"><?php echo h($t['status']); ?></span></td>
                            <td><?php echo (int)$t['pos_x']; ?>, <?php echo (int)$t['pos_y']; ?></td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary edit-table" data-json='<?php echo h(json_encode($t)); ?>'>Edit</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.compact-restaurant-hero{padding:12px 16px!important;margin-bottom:10px!important}
.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}
.table-modern thead th{font-size:.72rem;text-transform:uppercase;color:#64748b;background:#f8fafc;white-space:nowrap}
.table-modern td{vertical-align:middle}
.layout-help-note{border:1px solid #bfdbfe;background:linear-gradient(135deg,#eff6ff,#ffffff);border-radius:14px;padding:10px 12px;font-size:.82rem;color:#1e3a8a}
.layout-help-note strong{color:#0f172a}
.layout-grid-example{display:flex;flex-wrap:wrap;gap:6px;margin-top:7px}
.layout-grid-example span{display:inline-flex;align-items:center;padding:4px 8px;border-radius:999px;background:#fff;border:1px solid #dbeafe;color:#334155;font-size:.76rem;font-weight:700}
.form-text{font-size:.68rem;color:#64748b}
.duplicate-alert{border-left:5px solid #dc3545}
.is-duplicate-field{border:2px solid #dc3545!important;background:#fff5f5!important;box-shadow:0 0 0 .2rem rgba(220,53,69,.12)!important;animation:duplicateShake .25s linear 2}
@keyframes duplicateShake{0%{transform:translateX(0)}25%{transform:translateX(-4px)}50%{transform:translateX(4px)}75%{transform:translateX(-4px)}100%{transform:translateX(0)}}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const hadValidationError = <?php echo $formError ? 'true' : 'false'; ?>;
    const duplicateField = <?php echo json_encode($formErrorField); ?>;

    if (hadValidationError && duplicateField) {
        const field = document.getElementById(duplicateField);
        if (field) {
            setTimeout(function () {
                field.focus();
                if (typeof field.select === 'function') field.select();
            }, 300);
        }
    }

    document.querySelectorAll('.edit-area').forEach(function (b) {
        b.onclick = function () {
            const x = JSON.parse(this.dataset.json);
            area_id.value = x.id;
            area_name.value = x.area_name;
            area_sort.value = x.sort_order;
            area_active.value = x.is_active;
        };
    });

    document.querySelectorAll('.edit-table').forEach(function (b) {
        b.onclick = function () {
            const x = JSON.parse(this.dataset.json);
            table_id.value = x.id;
            table_area.value = x.area_id || '';
            table_no.value = x.table_no || '';
            table_name.value = x.table_name || '';
            table_seats.value = x.seats || 2;
            table_shape.value = x.shape || 'round';
            table_orientation.value = x.orientation || 'horizontal';
            table_x.value = x.pos_x || 0;
            table_y.value = x.pos_y || 0;
            table_status.value = x.status || 'available';
            table_active.value = x.is_active || 1;

            document.querySelectorAll('.is-duplicate-field').forEach(function (el) {
                el.classList.remove('is-duplicate-field');
            });

            window.scrollTo({top: 0, behavior: 'smooth'});
        };
    });
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
