<?php
/**
 * staff/includes/schema_heal.php
 * ---------------------------------------------------------------------------
 * Self-healing schema for the staff-module features (mirrors schema_staff.sql,
 * which could never run on MySQL 8.0 because "ADD COLUMN IF NOT EXISTS" is
 * MariaDB-only syntax). Runs idempotent, information_schema-guarded DDL so
 * the staff portal, kitchen rush flag and "Call Server" feature work without
 * a manual migration. Cached per session so it costs one check per login.
 */

if (!function_exists('dabil_staff_schema_heal')) {

    function dabil_col_exists(mysqli $conn, string $table, string $col): bool {
        $t = $conn->real_escape_string($table);
        $c = $conn->real_escape_string($col);
        $r = @$conn->query(
            "SELECT 1 FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$t' AND COLUMN_NAME = '$c' LIMIT 1"
        );
        return $r && $r->num_rows > 0;
    }

    function dabil_staff_schema_heal(mysqli $conn): void {
        if (!empty($_SESSION['__staff_schema_ok'])) return;
        try {
            $conn->query(
                "CREATE TABLE IF NOT EXISTS `service_calls` (
                    `id` INT NOT NULL AUTO_INCREMENT,
                    `restaurant_id` INT NOT NULL,
                    `order_id` INT DEFAULT NULL,
                    `user_id` INT DEFAULT NULL,
                    `table_number` VARCHAR(20) DEFAULT NULL,
                    `table_label` VARCHAR(120) DEFAULT NULL,
                    `customer_name` VARCHAR(150) DEFAULT NULL,
                    `status` ENUM('open','ack') NOT NULL DEFAULT 'open',
                    `acked_by` INT DEFAULT NULL,
                    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    `acked_at` TIMESTAMP NULL DEFAULT NULL,
                    PRIMARY KEY (`id`),
                    KEY `idx_rest_status` (`restaurant_id`, `status`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
            );
            if (!dabil_col_exists($conn, 'users', 'must_reset_pw')) {
                $conn->query("ALTER TABLE `users` ADD COLUMN `must_reset_pw` TINYINT(1) NOT NULL DEFAULT 0");
            }
            if (!dabil_col_exists($conn, 'orders', 'is_rushed')) {
                $conn->query("ALTER TABLE `orders` ADD COLUMN `is_rushed` TINYINT(1) NOT NULL DEFAULT 0");
            }
            if (!dabil_col_exists($conn, 'orders', 'table_label')) {
                $conn->query("ALTER TABLE `orders` ADD COLUMN `table_label` VARCHAR(120) NULL DEFAULT NULL AFTER `table_number`");
            }
            if (!dabil_col_exists($conn, 'menu_items', 'stock_qty')) {
                $conn->query("ALTER TABLE `menu_items` ADD COLUMN `stock_qty` INT NULL DEFAULT NULL AFTER `is_available`");
            }
            if (!dabil_col_exists($conn, 'restaurant_tables', 'area_type')) {
                $conn->query("ALTER TABLE `restaurant_tables` ADD COLUMN `area_type` ENUM('table','location') NOT NULL DEFAULT 'table' AFTER `table_number`");
            }
            $_SESSION['__staff_schema_ok'] = 1;
        } catch (\Throwable $e) {
            error_log('[dabil] staff schema heal failed: ' . $e->getMessage());
        }
    }
}
