<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method.');
}

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
    jsonResponse(false, 'Invalid CSRF token.');
}

$db = Database::getInstance();
$action = $_POST['action'] ?? 'save';
$userId = (int) ($_POST['user_id'] ?? 0);

switch ($action) {
    case 'toggle_status':
        $newStatus = trim($_POST['status'] ?? 'active');
        $db->update('users', ['status' => $newStatus, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$userId]);
        $activityLog = new ActivityLog();
        $activityLog->log($_SESSION['user_id'], null, 'user', 'status_change', 'Changed user #' . $userId . ' status to ' . $newStatus);
        jsonResponse(true, 'User status updated.');
        break;

    case 'reset_password':
        $password = $_POST['password'] ?? '';
        if (strlen($password) < 6) {
            jsonResponse(false, 'Password must be at least 6 characters.');
        }
        $db->update('users', ['password' => password_hash($password, PASSWORD_DEFAULT), 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$userId]);
        jsonResponse(true, 'Password reset successfully.');
        break;

    case 'save':
    default:
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $roleId = (int) ($_POST['role_id'] ?? 0);
        $restaurantId = !empty($_POST['restaurant_id']) ? (int) $_POST['restaurant_id'] : null;
        $status = trim($_POST['status'] ?? 'active');
        $password = $_POST['password'] ?? '';

        if (empty($name) || empty($email) || $roleId <= 0) {
            jsonResponse(false, 'Name, email, and role are required.');
        }

        $data = [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'role_id' => $roleId,
            'restaurant_id' => $restaurantId,
            'status' => $status,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        if ($userId > 0) {
            if (!empty($password)) {
                $data['password'] = password_hash($password, PASSWORD_DEFAULT);
            }
            $db->update('users', $data, 'id = ?', [$userId]);
            jsonResponse(true, 'User updated successfully.');
        } else {
            if (empty($password)) {
                jsonResponse(false, 'Password is required for new users.');
            }
            $existingEmail = $db->query("SELECT id FROM users WHERE email = ?", [$email])->fetch();
            if ($existingEmail) {
                jsonResponse(false, 'Email already exists.');
            }
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
            $data['created_at'] = date('Y-m-d H:i:s');
            $db->insert('users', $data);
            jsonResponse(true, 'User created successfully.');
        }
        break;
}
