<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

$page = isset($_GET["page"]) ? (int) $_GET["page"] : 1;
$limit = isset($_GET["limit"]) ? (int) $_GET["limit"] : 10;
$search = isset($_GET["search"]) ? $_GET["search"] : "";
$provinsi = isset($_GET["provinsi"]) ? $_GET["provinsi"] : "";
$kabupaten = isset($_GET["kabupaten"]) ? $_GET["kabupaten"] : "";
$status = isset($_GET["status"]) ? $_GET["status"] : "";

if ($page < 1) {
    $page = 1;
}

if ($limit < 1) {
    $limit = 10;
}

$offset = ($page - 1) * $limit;

$searchParam = "%" . $search . "%";
$provinsiParam = "%" . $provinsi . "%";
$kabupatenParam = "%" . $kabupaten . "%";
$statusParam = "%" . $status . "%";

$sql = "
    SELECT 
        id,
        nama,
        provinsi,
        kabupaten,
        alamat,
        foto,
        total_dana,
        jumlah_siswa,
        status,
        created_at
    FROM sppg
    WHERE nama LIKE ?
    AND provinsi LIKE ?
    AND kabupaten LIKE ?
    AND status LIKE ?
    ORDER BY id DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);

$stmt->bind_param(
    "ssssii",
    $searchParam,
    $provinsiParam,
    $kabupatenParam,
    $statusParam,
    $limit,
    $offset
);

$stmt->execute();

$result = $stmt->get_result();

$data = [];

while ($row = $result->fetch_assoc()) {
    $row["foto_url"] = !empty($row["foto"])
        ? "http://localhost/backend/" . $row["foto"]
        : null;

    $data[] = $row;
}

response(true, "Data SPPG berhasil diambil", $data);

?>