<?php
// api-users.php - CRUD users (kasir/admin)
require_once __DIR__ . '/config.php';

$method = $_SERVER['REQUEST_METHOD'];
$db = getDB();

switch ($method) {
    case 'GET':
        requireAdmin();
        try {
            $rows = $db->query('
                SELECT u.*, o.name AS outlet_name
                FROM users u
                LEFT JOIN outlets o ON u.outlet_id = o.id
                ORDER BY u.name
            ')->fetchAll();
        } catch (Exception $e) {
            $rows = [];
        }
        $users = [];
        foreach ($rows as $r) {
            $users[] = [
                'id' => (int)$r['id'],
                'name' => $r['name'],
                'email' => $r['email'],
                'role' => $r['role'],
                'outlet_id' => $r['outlet_id'] ? (int)$r['outlet_id'] : null,
                'outlet_name' => $r['outlet_name'],
            ];
        }
        jsonResponse(['status' => 'success', 'data' => $users]);
        break;

    case 'POST':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $name = trim($input['name'] ?? '');
        $email = trim($input['email'] ?? '');
        $password = $input['password'] ?? '';
        if (empty($name) || empty($email) || empty($password)) {
            jsonResponse(['status' => 'error', 'message' => 'Nama, email, dan password wajib diisi'], 400);
        }
        $stmt = $db->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            jsonResponse(['status' => 'error', 'message' => 'Email sudah dipakai'], 400);
        }
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $db->prepare('INSERT INTO users (name, email, password, role, outlet_id) VALUES (?,?,?,?,?)');
        $stmt->execute([
            $name,
            $email,
            $hash,
            $input['role'] ?? 'kasir',
            empty($input['outlet_id']) ? null : (int)$input['outlet_id'],
        ]);
        jsonResponse(['status' => 'success', 'id' => (int)$db->lastInsertId()]);
        break;

    case 'PUT':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $id = (int)($input['id'] ?? 0);
        if ($id <= 0) { jsonResponse(['status' => 'error', 'message' => 'ID tidak valid'], 400); }
        $name = trim($input['name'] ?? '');
        $email = trim($input['email'] ?? '');
        $role = $input['role'] ?? 'kasir';
        $outletId = empty($input['outlet_id']) ? null : (int)$input['outlet_id'];
        if (!empty($input['password'])) {
            $hash = password_hash($input['password'], PASSWORD_BCRYPT);
            $stmt = $db->prepare('UPDATE users SET name=?, email=?, password=?, role=?, outlet_id=? WHERE id=?');
            $stmt->execute([$name, $email, $hash, $role, $outletId, $id]);
        } else {
            $stmt = $db->prepare('UPDATE users SET name=?, email=?, role=?, outlet_id=? WHERE id=?');
            $stmt->execute([$name, $email, $role, $outletId, $id]);
        }
        jsonResponse(['status' => 'success']);
        break;

    case 'DELETE':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $id = (int)($input['id'] ?? 0);
        if ($id <= 0) { jsonResponse(['status' => 'error', 'message' => 'ID tidak valid'], 400); }
        $stmt = $db->prepare('DELETE FROM users WHERE id = ?');
        $stmt->execute([$id]);
        jsonResponse(['status' => 'success']);
        break;
}