<?php
// master_manage_settings.php
header("Content-Type: application/json; charset=UTF-8");

// Inklusi file keamanan dan autentikasi
require 'security.php';
require 'logger.php';
require 'rate_limit.php';
require 'authenticate.php';

// Cek metode request
$method = $_SERVER['REQUEST_METHOD'];
$allowed_methods = ['GET', 'POST', 'PUT', 'DELETE'];
if (!in_array($method, $allowed_methods)) {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on master_manage_settings.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Autentikasi: Hanya master_admin yang diizinkan
$user = authenticate($pdo, ['master_admin']);

// Terapkan rate limiting spesifik endpoint jika diperlukan
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 100, 60, $identifier);

// Mengambil ID pengaturan dari URL jika ada
$setting_id = null;
if (isset($_GET['id'])) {
    $setting_id = intval($_GET['id']);
}

// Handle setiap metode
switch ($method) {
    case 'GET':
        if ($setting_id) {
            // Ambil satu pengaturan
            try {
                $stmt = $pdo->prepare("SELECT * FROM settings WHERE id = ?");
                $stmt->execute([$setting_id]);
                $setting = $stmt->fetch();

                if (!$setting) {
                    http_response_code(404);
                    echo json_encode(['error' => 'Setting not found']);
                    log_activity("Setting ID $setting_id not found.");
                    exit;
                }

                http_response_code(200);
                echo json_encode(['setting' => $setting]);
                log_activity("Setting ID $setting_id retrieved by user_id: " . $user['id']);

            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_settings.php GET error: " . $e->getMessage());
                exit;
            }
        } else {
            // Ambil semua pengaturan
            try {
                $stmt = $pdo->prepare("SELECT * FROM settings");
                $stmt->execute();
                $settings = $stmt->fetchAll();

                http_response_code(200);
                echo json_encode(['settings' => $settings]);
                log_activity("All settings retrieved by user_id: " . $user['id']);

            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_settings.php GET all error: " . $e->getMessage());
                exit;
            }
        }
        break;

    case 'POST':
        // Tambah pengaturan baru
        $input = json_decode(file_get_contents('php://input'), true);
        $input = sanitize_input($input);

        $required_fields = ['key_name', 'value'];
        foreach ($required_fields as $field) {
            if (empty($input[$field])) {
                http_response_code(400);
                echo json_encode(['error' => "$field is required"]);
                log_activity("Missing $field in POST request.");
                exit;
            }
        }

        $key_name = $input['key_name'];
        $value = $input['value'];

        try {
            $stmt = $pdo->prepare("INSERT INTO settings (key_name, value) VALUES (?, ?)");
            $stmt->execute([$key_name, $value]);

            http_response_code(201);
            echo json_encode(['message' => 'Setting created successfully', 'setting_id' => $pdo->lastInsertId()]);
            log_activity("Setting '$key_name' created by user_id: " . $user['id']);

        } catch (PDOException $e) {
            if ($e->getCode() == 23000) { // Duplicate entry
                http_response_code(409);
                echo json_encode(['error' => 'Key name already exists']);
                log_activity("Duplicate key_name '$key_name' in POST request.");
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_settings.php POST error: " . $e->getMessage());
            }
            exit;
        }
        break;

    case 'PUT':
        // Update pengaturan
        if (!$setting_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Setting ID is required']);
            log_activity("Setting ID missing in PUT request.");
            exit;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $input = sanitize_input($input);

        $fields = ['key_name', 'value'];
        $update_fields = [];
        $params = [];

        foreach ($fields as $field) {
            if (isset($input[$field])) {
                $update_fields[] = "$field = ?";
                $params[] = $input[$field];
            }
        }

        if (empty($update_fields)) {
            http_response_code(400);
            echo json_encode(['error' => 'No fields to update']);
            log_activity("No fields to update in PUT request for Setting ID $setting_id.");
            exit;
        }

        $params[] = $setting_id;

        try {
            $stmt = $pdo->prepare("UPDATE settings SET " . implode(', ', $update_fields) . " WHERE id = ?");
            $stmt->execute($params);

            http_response_code(200);
            echo json_encode(['message' => 'Setting updated successfully']);
            log_activity("Setting ID $setting_id updated by user_id: " . $user['id']);

        } catch (PDOException $e) {
            if ($e->getCode() == 23000) { // Duplicate entry
                http_response_code(409);
                echo json_encode(['error' => 'Key name already exists']);
                log_activity("Duplicate key_name in PUT request for Setting ID $setting_id.");
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_settings.php PUT error: " . $e->getMessage());
            }
            exit;
        }
        break;

    case 'DELETE':
        // Hapus pengaturan
        if (!$setting_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Setting ID is required']);
            log_activity("Setting ID missing in DELETE request.");
            exit;
        }

        try {
            $stmt = $pdo->prepare("DELETE FROM settings WHERE id = ?");
            $stmt->execute([$setting_id]);

            http_response_code(200);
            echo json_encode(['message' => 'Setting deleted successfully']);
            log_activity("Setting ID $setting_id deleted by user_id: " . $user['id']);

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Server error']);
            log_activity("master_manage_settings.php DELETE error: " . $e->getMessage());
            exit;
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method Not Allowed']);
        log_activity("Method Not Allowed on master_manage_settings.php from IP: " . $_SERVER['REMOTE_ADDR']);
        exit;
}
?>
