<?php
// api-outlets.php
require_once __DIR__ . '/config.php';

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

switch ($method) {
    case 'GET':
        try {
            $rows = $db->query('SELECT * FROM outlets ORDER BY name')->fetchAll();
        } catch (Exception $e) {
            $rows = [];
        }
        $outlets = [];
        foreach ($rows as $r) {
            $outlets[] = [
                'id' => (int)$r['id'],
                'name' => $r['name'],
                'address' => $r['address'],
                'is_active' => (int)$r['is_active'],
            ];
        }
        jsonResponse(['status' => 'success', 'data' => $outlets]);
        break;

    case 'POST':
        requireAdmin();
        $input = json_decode(file_get_contents('php://input'), true);
        $name = trim($input['name'] ?? '');
        if (empty($name)) {
            jsonResponse(['status' => 'error', 'message' => 'Nama outlet wajib diisi'], 400);
        }
        $stmt = $db->prepare('INSERT INTO outlets (name, address, is_active) VALUES (?,?,?)');
        $stmt->execute([$name, $input['address'] ?? '', (int)($input['is_active'] ?? 1)]);
        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); }
        $stmt = $db->prepare('UPDATE outlets SET name=?, address=?, is_active=? WHERE id=?');
        $stmt->execute([trim($input['name'] ?? ''), $input['address'] ?? '', (int)($input['is_active'] ?? 1), $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 outlets WHERE id = ?');
        $stmt->execute([$id]);
        jsonResponse(['status' => 'success']);
        break;
}