<?php
// master_manage_cooperatives.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_cooperatives.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 koperasi dari URL jika ada
$cooperative_id = null;
if (isset($_GET['id'])) {
    $cooperative_id = intval($_GET['id']);
}

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

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

                http_response_code(200);
                echo json_encode(['cooperative' => $cooperative]);
                log_activity("Cooperative ID $cooperative_id retrieved by user_id: " . $user['id']);

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

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

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

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

        $required_fields = ['name', 'type'];
        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;
            }
        }

        $name = $input['name'];
        $type = $input['type'];
        $description = isset($input['description']) ? $input['description'] : null;

        try {
            $stmt = $pdo->prepare("INSERT INTO cooperatives (name, type, description) VALUES (?, ?, ?)");
            $stmt->execute([$name, $type, $description]);

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

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

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

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

        $fields = ['name', 'type', 'description'];
        $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 Cooperative ID $cooperative_id.");
            exit;
        }

        $params[] = $cooperative_id;

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

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

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

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

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

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

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Server error']);
            log_activity("master_manage_cooperatives.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_cooperatives.php from IP: " . $_SERVER['REMOTE_ADDR']);
        exit;
}
?>
