<?php
/**
 * Canteen Settings Save
 * POST action: save_general | save_biometrics
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_role(['admin', 'headteacher'], true);
canteen_require_active();

$conn   = getDBConnection();
$action = trim((string)($_POST['action'] ?? ''));

switch ($action) {

    // ── General settings ──────────────────────────────────────────────────────
    case 'save_general': {
        $qr_enabled      = isset($_POST['qr_enabled'])      ? 1 : 0;
        $manual_fallback = isset($_POST['manual_id_fallback']) ? 1 : 0;
        $qr_hours        = (int)($_POST['qr_validity_hours'] ?? 24);
        $auto_ai         = isset($_POST['auto_ai_report'])   ? 1 : 0;
        $refresh         = (int)($_POST['cook_dashboard_refresh_seconds'] ?? 30);
        $scanner_pin     = trim((string)($_POST['scanner_pin']  ?? ''));
        $cook_pin        = trim((string)($_POST['cook_pin']     ?? ''));

        // Validate
        if (!in_array($qr_hours,  [6, 12, 24], true)) $qr_hours = 24;
        if (!in_array($refresh, [15, 30, 60], true))  $refresh  = 30;

        // Must have at least QR or manual fallback enabled
        if (!$qr_enabled && !$manual_fallback) {
            echo json_encode(['success' => false,
                'message' => 'At least one verification method must stay enabled.']);
            exit;
        }

        // Fetch existing hashes (don't overwrite unless new PIN provided)
        $existing = canteen_get_settings();

        $scanner_hash = $existing['scanner_pin_hash'] ?? null;
        $cook_hash    = $existing['cook_pin_hash']    ?? null;

        if ($scanner_pin !== '') {
            if (!preg_match('/^\d{4,8}$/', $scanner_pin)) {
                echo json_encode(['success' => false,
                    'message' => 'Scanner PIN must be 4–8 digits.']);
                exit;
            }
            $scanner_hash = password_hash($scanner_pin, PASSWORD_BCRYPT);
        }

        if ($cook_pin !== '') {
            if (!preg_match('/^\d{4,8}$/', $cook_pin)) {
                echo json_encode(['success' => false,
                    'message' => 'Cook PIN must be 4–8 digits.']);
                exit;
            }
            $cook_hash = password_hash($cook_pin, PASSWORD_BCRYPT);
        }

        $stmt = $conn->prepare(
            "UPDATE canteen_settings SET
                qr_enabled                   = ?,
                manual_id_fallback           = ?,
                qr_validity_hours            = ?,
                auto_ai_report               = ?,
                cook_dashboard_refresh_seconds = ?,
                scanner_pin_hash             = ?,
                cook_pin_hash                = ?
             WHERE school_id = 1"
        );
        $stmt->bind_param('iiiiiss',
            $qr_enabled, $manual_fallback, $qr_hours, $auto_ai, $refresh,
            $scanner_hash, $cook_hash);
        $stmt->execute();
        $stmt->close();

        // Clear canteen settings session cache
        unset($_SESSION['canteen_settings'], $_SESSION['canteen_settings_ts']);

        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_settings_save',
            'General settings updated');

        echo json_encode(['success' => true, 'message' => 'Settings saved.']);
        break;
    }

    // ── Biometrics settings ───────────────────────────────────────────────────
    case 'save_biometrics': {
        $fingerprint = isset($_POST['fingerprint_enabled']) ? 1 : 0;
        $facial      = isset($_POST['facial_recognition_enabled']) ? 1 : 0;
        $fp_model    = substr(trim((string)($_POST['hardware_fingerprint_model'] ?? '')), 0, 100);
        $cam_model   = substr(trim((string)($_POST['hardware_webcam_model']      ?? '')), 0, 100);
        $confidence  = (float)($_POST['facial_min_confidence'] ?? 0.85);

        // Enforce minimum confidence server-side regardless of UI
        if ($confidence < 0.70) $confidence = 0.70;
        if ($confidence > 1.00) $confidence = 1.00;

        // Biometrics require acknowledgment checkbox
        if (($fingerprint || $facial) && empty($_POST['hardware_acknowledged'])) {
            echo json_encode(['success' => false,
                'message' => 'You must acknowledge the hardware requirements before enabling biometrics.']);
            exit;
        }

        $stmt = $conn->prepare(
            "UPDATE canteen_settings SET
                fingerprint_enabled          = ?,
                facial_recognition_enabled   = ?,
                hardware_fingerprint_model   = ?,
                hardware_webcam_model        = ?,
                facial_min_confidence        = ?
             WHERE school_id = 1"
        );
        $stmt->bind_param('iissd', $fingerprint, $facial, $fp_model, $cam_model, $confidence);
        $stmt->execute();
        $stmt->close();

        unset($_SESSION['canteen_settings'], $_SESSION['canteen_settings_ts']);

        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_settings_save',
            'Biometrics settings updated');

        echo json_encode(['success' => true, 'message' => 'Biometric settings saved.']);
        break;
    }

    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action.']);
}

$conn->close();
