<?php
/**
 * Staff session guard. Include at the top of every authenticated staff page
 * (before any output). Redirects to login if not signed in as waiter/staff.
 * Exposes: $staff (row), $__staff_id, $__staff_role, $__rest_id,
 * $__rest_name, $__name, $__avatar_url, $__portal ('waiter'|'kitchen').
 */
if (session_status() === PHP_SESSION_NONE) session_start();
include_once(__DIR__ . "/../config/db.php");
include_once(__DIR__ . "/schema_heal.php");
dabil_staff_schema_heal($conn);

if (empty($_SESSION['staff_id']) || !in_array($_SESSION['staff_role'] ?? '', ['waiter', 'staff'], true)) {
    header("Location: login.php");
    exit;
}

$__staff_id = (int)$_SESSION['staff_id'];

$stmt = $conn->prepare(
    "SELECT u.id, u.name, u.email, u.phone, u.avatar, u.role, u.status, u.restaurant_id,
            r.name AS restaurant_name, r.status AS restaurant_status
     FROM users u LEFT JOIN restaurants r ON u.restaurant_id = r.id
     WHERE u.id = ? AND u.role IN ('waiter','staff') LIMIT 1"
);
$stmt->bind_param("i", $__staff_id);
$stmt->execute();
$staff = $stmt->get_result()->fetch_assoc();

if (!$staff || (int)$staff['status'] !== 1) {
    session_destroy();
    header("Location: login.php?err=inactive");
    exit;
}

$__staff_role = $staff['role'];
$__rest_id    = (int)$staff['restaurant_id'];
$__rest_name  = $staff['restaurant_name'] ?? 'Your Restaurant';
$__name       = $staff['name'] ?? 'Staff';
$__portal     = $__staff_role === 'waiter' ? 'waiter' : 'kitchen';

$__initials = strtoupper(substr($__name, 0, 1)) . (strpos($__name, ' ') !== false ? strtoupper(substr(strrchr($__name, ' '), 1, 1)) : '');
$__avatar_url = '';
if (!empty($staff['avatar']) && file_exists(__DIR__ . '/../../customer/uploads/avatars/' . $staff['avatar'])) {
    // staff avatars (if any) share the customer upload location
    $__avatar_url = '../customer/uploads/avatars/' . $staff['avatar'];
}

/**
 * Forced first-time password reset (defensive — column added by
 * schema_staff.sql). If must_reset_pw = 1, push the user to set a new one.
 */
$__must_reset = false;
if ($chk = $conn->prepare("SELECT must_reset_pw FROM users WHERE id=?")) {
    $chk->bind_param("i", $__staff_id); $chk->execute();
    $__must_reset = (bool)($chk->get_result()->fetch_assoc()['must_reset_pw'] ?? 0);
}
$__self = basename($_SERVER['PHP_SELF']);
if ($__must_reset && $__self !== 'change_password.php' && $__self !== 'logout.php') {
    header("Location: change_password.php?first=1");
    exit;
}

/**
 * Human-readable order source from its QR location.
 * Returns [primary, secondary]:
 *   - dine-in:      ["Table 14", "Main dining area"]   (label = area/section)
 *   - office/org:   ["Marketing Office", "3rd Floor"]  (table_number = office id, label = section)
 *   - online/pickup ["Online / Pickup", ""]
 * Pass a row that includes table_number and loc_label (restaurant_tables.label).
 */
function order_source_label(array $o): array {
    $label = trim((string)($o['loc_label'] ?? ''));
    $tn    = trim((string)($o['table_number'] ?? ''));
    if ($tn !== '') {
        // If the table_number itself reads like a place (letters), show it as the
        // name; otherwise treat it as a numbered table.
        $primary = preg_match('/^[0-9]+$/', $tn) ? 'Table ' . $tn : $tn;
        return [$primary, $label];
    }
    if ($label !== '') return [$label, ''];
    return ['Online / Pickup', ''];
}
