<?php
require_once dirname(__DIR__, 2) . '/include/con_data.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$action = $_POST['action'] ?? '';

try {
    if ($action === 'add') {
        $username = $_POST['username'];
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $role = $_POST['role'];
        $shop_id = !empty($_POST['shop_id']) ? $_POST['shop_id'] : null;
        $status = $_POST['status'];

        // Check if username exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetchColumn() > 0) {
            echo json_encode(['success' => false, 'message' => 'Username already exists']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO users (username, name, email, password, role, shop_id, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$username, $name, $email, $password, $role, $shop_id, $status]);

        echo json_encode(['success' => true]);

    } elseif ($action === 'edit') {
        $user_id = $_POST['user_id'];
        $username = $_POST['username'];
        $name = $_POST['name'];
        $email = $_POST['email'];
        $role = $_POST['role'];
        $shop_id = !empty($_POST['shop_id']) ? $_POST['shop_id'] : null;
        $status = $_POST['status'];

        // Check password update
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET username=?, name=?, email=?, password=?, role=?, shop_id=?, status=? WHERE user_id=?");
            $stmt->execute([$username, $name, $email, $password, $role, $shop_id, $status, $user_id]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET username=?, name=?, email=?, role=?, shop_id=?, status=? WHERE user_id=?");
            $stmt->execute([$username, $name, $email, $role, $shop_id, $status, $user_id]);
        }

        echo json_encode(['success' => true]);

    } elseif ($action === 'delete') {
        $user_id = $_POST['user_id'];
        // Prevent deleting self? Or leave it flexible.
        // Maybe check if it's the last superadmin?

        $stmt = $pdo->prepare("DELETE FROM users WHERE user_id = ?");
        $stmt->execute([$user_id]);

        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
}
