<?php
// api/kebutuhan.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once '../config/db.php';
require_once 'middleware.php';

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            $currentUser = optionalAuth();
            $id = isset($_GET['id']) ? (int)$_GET['id'] : null;

            if ($id) {
                $stmt = $pdo->prepare(
                    "SELECT k.*, ri.nama AS nama_rumah_ibadah, ri.alamat, ri.latitude, ri.longitude,
                           COALESCE(SUM(CASE WHEN ko.status = 'confirmed' THEN ko.jumlah ELSE 0 END), 0) AS jumlah_terkumpul
                    FROM kebutuhan k
                    JOIN rumah_ibadah ri ON k.rumah_ibadah_id = ri.id
                    LEFT JOIN kontribusi ko ON k.id = ko.kebutuhan_id
                    WHERE k.id = ?
                    GROUP BY k.id"
                );
                $stmt->execute([$id]);
                $row = $stmt->fetch();

                if ($row) {
                    $row['sisa_kebutuhan'] = max(0, (float)$row['jumlah_dibutuhkan'] - (float)$row['jumlah_terkumpul']);
                    echo json_encode(['success' => true, 'data' => $row, 'viewer_role' => $currentUser ? $currentUser['role'] : 'guest']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Kebutuhan tidak ditemukan']);
                }
            } else {
                $sql = "SELECT k.*, ri.nama AS nama_rumah_ibadah, ri.alamat, ri.latitude, ri.longitude,
                           COALESCE(SUM(CASE WHEN ko.status = 'confirmed' THEN ko.jumlah ELSE 0 END), 0) AS jumlah_terkumpul
                    FROM kebutuhan k
                    JOIN rumah_ibadah ri ON k.rumah_ibadah_id = ri.id
                    LEFT JOIN kontribusi ko ON k.id = ko.kebutuhan_id
                    GROUP BY k.id
                    ORDER BY k.created_at DESC";

                $rows = $pdo->query($sql)->fetchAll();
                foreach ($rows as &$r) {
                    $r['sisa_kebutuhan'] = max(0, (float)$r['jumlah_dibutuhkan'] - (float)$r['jumlah_terkumpul']);
                }

                echo json_encode(['success' => true, 'data' => $rows, 'viewer_role' => $currentUser ? $currentUser['role'] : 'guest']);
            }
            break;

        case 'POST':
            $currentUser = requireAuth(['admin', 'koordinator']);
            $body = json_decode(file_get_contents('php://input'), true) ?: $_POST;

            $rumahIbadahId = (int)($body['rumah_ibadah_id'] ?? 0);
            $jenisBantuan  = trim($body['jenis_bantuan'] ?? '');
            $kategori      = trim($body['kategori'] ?? 'barang');
            $satuan        = trim($body['satuan'] ?? 'unit');
            $jumlahReq     = (float)($body['jumlah_dibutuhkan'] ?? 0);

            if ($currentUser['role'] === 'koordinator' && $currentUser['rumah_ibadah_id'] != $rumahIbadahId) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Koordinator hanya dapat mengelola kebutuhan rumah ibadah mereka sendiri.']);
                exit;
            }

            $allowedSatuan = ['unit','orang','jam','shift','nominal'];
            if (!in_array($satuan, $allowedSatuan)) $satuan = 'unit';

            if (!$rumahIbadahId || !$jenisBantuan || $jumlahReq <= 0) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Parameter input tidak valid atau jumlah harus lebih besar dari 0']);
                exit;
            }

            try {
                $stmt = $pdo->prepare("INSERT INTO kebutuhan (rumah_ibadah_id, jenis_bantuan, kategori, jumlah_dibutuhkan, satuan) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$rumahIbadahId, $jenisBantuan, $kategori, $jumlahReq, $satuan]);
            } catch (PDOException $e) {
                $stmt = $pdo->prepare("INSERT INTO kebutuhan (rumah_ibadah_id, jenis_bantuan, kategori, jumlah_dibutuhkan) VALUES (?, ?, ?, ?)");
                $stmt->execute([$rumahIbadahId, $jenisBantuan, $kategori, $jumlahReq]);
            }

            echo json_encode(['success' => true, 'message' => 'Kebutuhan bantuan berhasil ditambahkan', 'id' => $pdo->lastInsertId()]);
            break;

        case 'PUT':
            $currentUser = requireAuth(['admin', 'koordinator']);
            $body = json_decode(file_get_contents('php://input'), true) ?: $_POST;
            $id = (int)($body['id'] ?? 0);

            $stmt = $pdo->prepare("SELECT rumah_ibadah_id FROM kebutuhan WHERE id = ?");
            $stmt->execute([$id]);
            $kebutuhan = $stmt->fetch();

            if (!$kebutuhan) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Kebutuhan tidak ditemukan']);
                exit;
            }

            if ($currentUser['role'] === 'koordinator' && $currentUser['rumah_ibadah_id'] != $kebutuhan['rumah_ibadah_id']) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Koordinator tidak berhak merubah kebutuhan rumah ibadah lain.']);
                exit;
            }

            $satuanIn = trim($body['satuan'] ?? 'unit');
            $allowedSatuan = ['unit','orang','jam','shift','nominal'];
            if (!in_array($satuanIn, $allowedSatuan)) $satuanIn = 'unit';

            try {
                $stmt = $pdo->prepare("UPDATE kebutuhan SET jenis_bantuan = ?, kategori = ?, jumlah_dibutuhkan = ?, satuan = ? WHERE id = ?");
                $stmt->execute([
                    trim($body['jenis_bantuan']),
                    trim($body['kategori']),
                    (float)$body['jumlah_dibutuhkan'],
                    $satuanIn,
                    $id
                ]);
            } catch (PDOException $e) {
                $stmt = $pdo->prepare("UPDATE kebutuhan SET jenis_bantuan = ?, kategori = ?, jumlah_dibutuhkan = ? WHERE id = ?");
                $stmt->execute([
                    trim($body['jenis_bantuan']),
                    trim($body['kategori']),
                    (float)$body['jumlah_dibutuhkan'],
                    $id
                ]);
            }

            echo json_encode(['success' => true, 'message' => 'Kebutuhan berhasil diperbarui']);
            break;

        case 'DELETE':
            $currentUser = requireAuth(['admin', 'koordinator']);
            $id = (int)($_GET['id'] ?? 0);

            $stmt = $pdo->prepare("SELECT rumah_ibadah_id FROM kebutuhan WHERE id = ?");
            $stmt->execute([$id]);
            $kebutuhan = $stmt->fetch();

            if (!$kebutuhan) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Kebutuhan tidak ditemukan']);
                exit;
            }

            if ($currentUser['role'] === 'koordinator' && $currentUser['rumah_ibadah_id'] != $kebutuhan['rumah_ibadah_id']) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Koordinator tidak berhak menghapus kebutuhan rumah ibadah lain.']);
                exit;
            }

            $stmt = $pdo->prepare("DELETE FROM kebutuhan WHERE id = ?");
            $stmt->execute([$id]);

            echo json_encode(['success' => true, 'message' => 'Kebutuhan berhasil dihapus']);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
