<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireRole(['restaurant_admin']);

$csrf = new CSRF();
$restaurantId = $auth->restaurantId();
$userId = $auth->userId();
$db = Database::getInstance();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' && $action === 'get') {
    $id = (int)($_GET['id'] ?? 0);
    $staff = $db->query("SELECT u.*, r.name as role_name FROM users u INNER JOIN roles r ON u.role_id = r.id WHERE u.id = ? AND u.restaurant_id = ?", [$id, $restaurantId])->fetch();
    if ($staff) {
        unset($staff['password']);
        jsonResponse(true, 'ok', ['staff' => $staff]);
    }
    jsonResponse(false, 'Not found');
}

if ($method === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['staff_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $roleId = (int)($_POST['role_id'] ?? 0);
        $password = $_POST['password'] ?? '';
        $status = $_POST['status'] ?? 'active';

        if (empty($name)) jsonResponse(false, 'Name is required');
        if (empty($email)) jsonResponse(false, 'Email is required');

        $validRoles = [2, 3, 4, 5, 6];
        if (!in_array($roleId, $validRoles)) jsonResponse(false, 'Invalid role');

        if ($action === 'add') {
            if (empty($password) || strlen($password) < 6) jsonResponse(false, 'Password must be at least 6 characters');

            $existing = $db->query("SELECT id FROM users WHERE email = ?", [$email])->fetch();
            if ($existing) jsonResponse(false, 'Email already exists');

            $db->insert('users', [
                'role_id' => $roleId,
                'restaurant_id' => $restaurantId,
                'name' => $name,
                'email' => $email,
                'password' => password_hash($password, PASSWORD_DEFAULT),
                'phone' => $phone,
                'status' => $status,
            ]);
            jsonResponse(true, 'Staff member added successfully');
        } else {
            $existing = $db->query("SELECT id FROM users WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
            if (!$existing) jsonResponse(false, 'Staff not found');

            $updateData = [
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'role_id' => $roleId,
                'status' => $status,
            ];

            if (!empty($password) && strlen($password) >= 6) {
                $updateData['password'] = password_hash($password, PASSWORD_DEFAULT);
            }

            $emailCheck = $db->query("SELECT id FROM users WHERE email = ? AND id != ?", [$email, $id])->fetch();
            if ($emailCheck) jsonResponse(false, 'Email already in use');

            $db->update('users', $updateData, 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
            jsonResponse(true, 'Staff updated successfully');
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === $userId) jsonResponse(false, 'Cannot delete yourself');

        $staff = $db->query("SELECT id, name FROM users WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$staff) jsonResponse(false, 'Staff not found');

        $db->delete('users', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Staff member deleted');
    }

    if ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id === $userId) jsonResponse(false, 'Cannot change your own status');

        $staff = $db->query("SELECT id, status FROM users WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$staff) jsonResponse(false, 'Staff not found');

        $newStatus = $staff['status'] === 'active' ? 'inactive' : 'active';
        $db->update('users', ['status' => $newStatus], 'id = ?', [$id]);
        jsonResponse(true, 'Staff ' . ($newStatus === 'active' ? 'activated' : 'deactivated'));
    }
}

jsonResponse(false, 'Invalid request');
