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

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

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

                http_response_code(200);
                echo json_encode(['due' => $due]);
                log_activity("Due ID $due_id retrieved by user_id: " . $user['id']);

            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_dues.php GET error: " . $e->getMessage());
                exit;
            }
        } else {
            // Ambil semua iuran
            try {
                $stmt = $pdo->prepare("SELECT dues.*, cooperatives.name as cooperative_name FROM dues 
                                       JOIN cooperatives ON dues.cooperative_id = cooperatives.id");
                $stmt->execute();
                $dues = $stmt->fetchAll();

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

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

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

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

        $cooperative_id = intval($input['cooperative_id']);
        $name = $input['name'];
        $amount = floatval($input['amount']);
        $frequency = $input['frequency'];

        // Validasi frequency
        $valid_frequencies = ['monthly', 'quarterly', 'yearly'];
        if (!in_array($frequency, $valid_frequencies)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid frequency value']);
            log_activity("Invalid frequency value '$frequency' in POST request.");
            exit;
        }

        try {
            // Pastikan koperasi ada
            $stmt = $pdo->prepare("SELECT id FROM cooperatives WHERE id = ?");
            $stmt->execute([$cooperative_id]);
            if (!$stmt->fetch()) {
                http_response_code(404);
                echo json_encode(['error' => 'Cooperative not found']);
                log_activity("Cooperative ID $cooperative_id not found in POST request.");
                exit;
            }

            // Insert iuran
            $stmt = $pdo->prepare("INSERT INTO dues (cooperative_id, name, amount, frequency) VALUES (?, ?, ?, ?)");
            $stmt->execute([$cooperative_id, $name, $amount, $frequency]);

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

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

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

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

        $fields = ['cooperative_id', 'name', 'amount', 'frequency'];
        $update_fields = [];
        $params = [];

        foreach ($fields as $field) {
            if (isset($input[$field])) {
                if ($field === 'frequency') {
                    $valid_frequencies = ['monthly', 'quarterly', 'yearly'];
                    if (!in_array($input[$field], $valid_frequencies)) {
                        http_response_code(400);
                        echo json_encode(['error' => 'Invalid frequency value']);
                        log_activity("Invalid frequency value '$input[$field]' in PUT request.");
                        exit;
                    }
                }
                $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 Due ID $due_id.");
            exit;
        }

        // Jika cooperative_id diupdate, pastikan koperasi tersebut ada
        if (isset($input['cooperative_id'])) {
            $cooperative_id = intval($input['cooperative_id']);
            $stmt = $pdo->prepare("SELECT id FROM cooperatives WHERE id = ?");
            $stmt->execute([$cooperative_id]);
            if (!$stmt->fetch()) {
                http_response_code(404);
                echo json_encode(['error' => 'Cooperative not found']);
                log_activity("Cooperative ID $cooperative_id not found in PUT request.");
                exit;
            }
        }

        $params[] = $due_id;

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

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

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

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

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

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

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