<?php

use Slim\Http\Request;
use Slim\Http\Response;

include 'fungsi-api-bot.php';
include 'fungsi-produksi.php';

// Routes

$app->get('/[{name}]', function (Request $request, Response $response, array $args) {
    // Sample log message
    $this->logger->info("Slim-Skeleton '/' route");

    // Render index view
    return $this->renderer->render($response, 'index.phtml', $args);
});

$app->get("/tadarus/{id}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    date_default_timezone_set("Asia/Bangkok");
    $tanggal = date("Y-m-d");

    $sql = "SELECT ayat_maqro, aksi FROM setoran_ayat JOIN anggota_tadarus ON anggota_tadarus.no_anggota=setoran_ayat.nik_tugas JOIN bot_telegram ON bot_telegram.nik=anggota_tadarus.id_anggota WHERE id_telegram=:id AND tanggal=:tanggal ";
    $stmt = $this->db->prepare($sql);
    $stmt->BindParam(":id", $id);
    $stmt->BindParam(":tanggal", $tanggal);
    $stmt->execute();
    $result = $stmt->fetch();
    $ayat_maqro = GetRangeAyat($result['ayat_maqro'], $tanggal);
    $ayat = GetAyat($ayat_maqro);

    if ($result['aksi'] == 'Klaim') :
        echo '*' . $ayat . '* ❎';
        echo "\n\n🆗 /sudahbaca";
    elseif ($result['aksi'] == 'Baca') :
        echo '*' . $ayat . '* ✅';
    else :
        echo "Tidak ada tadarus karena belum isi Daily Activity, silahkan segera isi Daily Activity di sistem.\n";
        echo "\n\nSubmit 👉🏻 http://berkah.nizzam.net";
    endif;
});

# update status tadarus jadi Baca
$app->get("/tadarusok/{id}", function (Request $request, Response $response, $args) {
    $id = $args["id"];

    $sql = "SELECT aksi, nik_tugas FROM setoran_ayat JOIN anggota_tadarus ON anggota_tadarus.no_anggota=setoran_ayat.nik_tugas JOIN bot_telegram ON bot_telegram.nik=anggota_tadarus.id_anggota WHERE id_telegram='" . $id . "' AND aksi='Klaim' ";
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetch();
    if ($result) {
        $sql_update = "UPDATE setoran_ayat SET aksi='Baca' WHERE nik_tugas=:nik_tugas AND aksi='Klaim'";
        $stmt_update = $this->db->prepare($sql_update);
        $stmt_update->BindParam(":nik_tugas", $result["nik_tugas"]);

        if ($stmt_update->execute())
            echo "✅ Alhamdulillah.. tadarus sudah selesai, semoga dicatat menjadi amal kebaikan.  Terimakasih 🙏🏻\n\n";
        echo "*Cek tadarus?* /tadarus";
    } else {
        echo "Maaf, tidak ada tadarus yang harus dibaca.";
    }
});

# buat bot telegram 
$app->get("/farmsakit/{id}/{unit}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $unit = $args["unit"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'farm_sakit', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "🆘 *Data Ayam Sakit*\n\n";
        echo detail_farm_sakit($unit);
    } else {
        echo "⛔️ *GAGAL:* _Anda tidak mempunyai akses untuk menu ini!_";
    }
});

# buat cron job kirim telegram dikirim setiap hari jam 10
$app->get("/farmsakit/", function (Request $request, Response $response) {
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'cron_farm_sakit']);

    $isi_text = "✉️ _Laporan Otomatis_\n\n";
    $isi_text .= "🆘 *Data Ayam Sakit*\n\n";
    $isi_text .= detail_farm_sakit("allunit");

    while ($bot = $stmt->fetch()) {
        $chatid = $bot['id_telegram'];
        $text = $isi_text;

        $data = array(
            'chat_id' => $chatid,
            'text'  => $text,
            'parse_mode' => 'Markdown'
        );

        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents('https://api.telegram.org/bot491297353:AAG_wbEJWRl7QSpzBSoTOjJUK1B8J4yqDqg/sendMessage', false, $context);
        //print_r($result);
    }
});

# untuk bot telegram data absensi Berkah 
$app->get("/absen/{id}/{tgl}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $tanggal = $args["tgl"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'absen', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "📙 *ABSENSI BGB*\n";
        echo "🗓 `" . tanggal($tanggal) . "`\n\n";
        echo getAbsensiBerkah($tanggal);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# buat cron job kirim telegram setiap hari jam 9
$app->get("/absen/", function (Request $request, Response $response) {
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'cron_absen']);

    # ambil tanggal sekarang
    date_default_timezone_set('Asia/Jakarta');
    $tanggal = date('Y-m-d');

    $isi_text = "✉️ _Laporan Otomatis_\n\n";
    $isi_text .= "📙 *ABSENSI BGB*\n";
    $isi_text .= "🗓 `" . tanggal($tanggal) . "`\n\n";
    $isi_text .= getAbsensiBerkah($tanggal);

    while ($bot = $stmt->fetch()) {
        $chatid = $bot['id_telegram'];
        $text = $isi_text;

        $data = array(
            'chat_id' => $chatid,
            'text'  => $text,
            'parse_mode' => 'Markdown'
        );

        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents('https://api.telegram.org/bot491297353:AAG_wbEJWRl7QSpzBSoTOjJUK1B8J4yqDqg/sendMessage', false, $context);
        //print_r($result);
    }
});

# untuk bot telegram data absensi sopir
$app->get("/absensopir/{id}/{tgl}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $tanggal = $args["tgl"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'absensopir', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "✅ *Absensi Sopir BGT*\n";
        echo "🗓 " . tanggal($tanggal) . "\n\n";
        echo getAbsensiSopir($tanggal);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# untuk bot telegram stok ayam berdasarkan umur
$app->get("/stok/{id}/{umur1}/{umur2}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $umur1 = $args["umur1"];
    $umur2 = $args["umur2"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'stok', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "🐥 *STOK AYAM*\n";
        echo "🗓 `" . $umur1 . "-" . $umur2 . "` Hari\n\n";
        echo getStokAyam($umur1, $umur2);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# untuk bot telegram cari data wajib panen sakit bobot > 1 kg
$app->get("/wajibpanensakit/{id}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'wajibpanensakit', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "‼️ *WAJIB PANEN*\n";
        echo "🐔 `SAKIT`\n\n";
        echo getWajibPanenSakit();
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# untuk bot telegram cari data wajib panen poor bobot > 1 kg
$app->get("/wajibpanenpoor/{id}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'wajibpanenpoor', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "‼️ *WAJIB PANEN*\n";
        echo "🐔 `ADG POOR`\n\n";
        echo getWajibPanenPoor();
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# untuk bot telegram cari data farm status awas
$app->get("/statusawas/{id}/{unit}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $unit = $args["unit"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'statusawas', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "⚠️ *STATUS AWAS*\n";
        echo getStatusAwas($unit);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});

# untuk bot telegram data laporan Tadarus
$app->get("/sudahtadarus/{id}/{tgl}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $tanggal = $args["tgl"];
    $status = $args["status"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'laporan_tadarus', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "📙 *LAPORAN SUDAH TADARUS*\n";
        echo "🗓 `" . tanggal($tanggal) . "`\n";
        echo getSudahTadarus($tanggal);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!!!_";
    }
});

# untuk bot telegram data laporan Tadarus belum baca
$app->get("/belumtadarus/{id}/{tgl}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $tanggal = $args["tgl"];
    $status = $args["status"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'laporan_tadarus', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "📙 *LAPORAN BELUM TADARUS*\n";
        echo "🗓 `" . tanggal($tanggal) . "`\n";
        echo getBelumTadarus($tanggal);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!!!_";
    }
});

# buat cron job kirim telegram setiap hari jam 9
$app->get("/resumeproduksi/", function (Request $request, Response $response) {
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'cron_resume_produksi']);

    # ambil tanggal sekarang
    date_default_timezone_set('Asia/Jakarta');
    $tanggal = date('Y-m-d');

    $isi_text = "✉️ _Laporan Otomatis_\n\n";
    $isi_text .= "🗂 *RESUME PRODUKSI BERKAH GROUP*\n";
    $isi_text .= "🗓 `" . tanggal($tanggal) . "`\n\n";
    $isi_text .= getResumeProduksi($tanggal);

    //    echo $isi_text;

    while ($bot = $stmt->fetch()) {
        $chatid = $bot['id_telegram'];
        $text = $isi_text;

        $data = array(
            'chat_id' => $chatid,
            'text'  => $text,
            'parse_mode' => 'Markdown'
        );

        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents('https://api.telegram.org/bot491297353:AAG_wbEJWRl7QSpzBSoTOjJUK1B8J4yqDqg/sendMessage', false, $context);
        //print_r($result);
    }
});

# untuk bot telegram data resume produksi
$app->get("/getresumeproduksi/{id}/{tgl}", function (Request $request, Response $response, $args) {
    $id = $args["id"];
    $tanggal = $args["tgl"];
    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:nama_group AND id_telegram=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":nama_group" => 'resumeproduksi', ":id" => $id]);

    if ($stmt->fetchColumn() > 0) {
        echo "🗂 *RESUME PRODUKSI BERKAH GROUP*\n";
        echo "🗓 " . tanggal($tanggal) . "\n\n";
        echo getResumeProduksi($tanggal);
    } else {
        echo "⛔️ *GAGAL:* _Maaf, Anda tidak mempunyai akses!_";
    }
});


$app->post("/abs_id_telegram/", function (Request $request, Response $response) {

    $daftar = $request->getParsedBody();
    simpanIdTelegramHK($daftar["nik"], $daftar["id_telegram"]);
});


$app->get("/cetak/", function (Request $request, Response $response, $args) {

    //    include 'fungsi-koperasi.php';

    $chatid = '128518319';
    echo cetak();

    // $data = array(
    //     'chat_id' => $chatid,
    //     'text'  => $text,
    //     'parse_mode' => 'Markdown',
    // //    'reply_to_message_id' => $msgid   // <---- biar ada reply nya balasannya, opsional, bisa dihapus baris ini
    // );

    // $options = array(
    //     'http' => array(
    //         'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    //         'method'  => 'POST',
    //         'content' => http_build_query($data),
    //     ),
    // );
    // $context  = stream_context_create($options); 
    // $result = file_get_contents('https://api.telegram.org/bot491297353:AAG_wbEJWRl7QSpzBSoTOjJUK1B8J4yqDqg/sendMessage', false, $context); 
    //print_r($result);

});

# untuk bot telegram data laporan Tadarus
$app->get("/login/", function (Request $request, Response $response, $args) {
    $username = $request->getQueryParam("user");
    $password = $request->getQueryParam("pass");
    // $username = $args["username"];
    // $password = $args["password"];

    $sql = "SELECT nik, hak_akses FROM login WHERE username=:username AND password=:password";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":username" => $username, ":password" => md5($password)]);
    $result = $stmt->fetchAll();

    if (COUNT($result) > 0) {
        return $response->withJson(["status" => "success", "token" => "1"], 200);
    } else {
        return $response->withJson(["status" => "failed", "token" => "1"], 200);
    }

    //return $response->withJson(["status" => "verified", "token" => $password, "userData" => $result], 200);

});


$app->get("/bgt_piutang_sa/", function (Request $request, Response $response, $args) {

    $sql = "SELECT id_telegram FROM bot_group WHERE nama_group=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([":id" => 'bgt_piutang_mingguan']);

    while ($bot = $stmt->fetch()) {
        $chatid = $bot['id_telegram'];
        $text = '_Data_ piutang *BGT!!!!*';

        $data = array(
            'chat_id' => $chatid,
            'text'  => $text,
            'parse_mode' => 'Markdown',
            //    'reply_to_message_id' => $msgid   // <---- biar ada reply nya balasannya, opsional, bisa dihapus baris ini
        );

        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents('https://api.telegram.org/bot491297353:AAG_wbEJWRl7QSpzBSoTOjJUK1B8J4yqDqg/sendMessage', false, $context);
        //print_r($result);
    }
});




/* ----------------------------------------------- */
/* ----------------- CHECK POINT ----------------- */
/* ----------------------------------------------- */


$app->get("/karyawan/login", function (Request $request, Response $response, $args) {
    $nik = $request->getQueryParam("nik");
    $sql = "SELECT nik,nama FROM karyawan WHERE nik = '$nik'";
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if ($result) {
        $st = "1";
    } else {
        $st = "0";
    }
    return $response->withJson(["status" => $st, "data" => $result,], 200);
});
$app->get("/karyawan/", function (Request $request, Response $response) {
    $sql = "SELECT nik,nama FROM karyawan WHERE nik LIKE '%000200040212%'";
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $response->withJson(["data" => $result], 200);
});
$app->get("/karyawan/pilih_farmer", function (Request $request, Response $response) {
    $nik = $request->getQueryParam("nik");
    $unit = $request->getQueryParam("unit");
    $sql  = "SELECT DISTINCT  e.id_farm , c.id_produksi, e.nama as nama_farmer, e.desa, c.periode FROM berkahgl_portal.konverter AS a JOIN berkahgl_" . $unit . ".karyawan as b JOIN berkahgl_" . $unit . ".produksi as c JOIN berkahgl_" . $unit . ".rhpp as d JOIN berkahgl_" . $unit . ".farm as e JOIN berkahgl_" . $unit . ".farm_update as f on a.niklama = b.nip and c.ts = b.nip and c.id_produksi = d.id_produksi and e.id_farm=d.id_farm and e.id_farm = c.id_farm and e.id_farm = f.idfarm WHERE d.panenbulan ='0000-00-00' and f.status ='1' and a.nikbaru='$nik' order by nama_farmer ASC";
    echo $sql;
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if ($result) {
        $st = "1";
    } else {
        $st = "0";
    }
    return $response->withJson(["status" => $st, "data" => $result,], 200);
});
$app->get("/karyawan/pilih_farmer/", function (Request $request, Response $response) {
    $id_farm =  $request->getQueryParam("id_farm");
    $id_produksi =  $request->getQueryParam("id_produksi");
    $unit = $request->getQueryParam("unit");
    $sql = "SELECT DISTINCT a.nama, a.id_farm,a.kec_peternak as alamat, b.qty as populasi, c.id_produksi,b.tanggal as date_chik_in,(SELECT DISTINCT SUM(b.qty) AS pakan FROM berkahgl_" . $unit . ".farm as a JOIN berkahgl_" . $unit . ".jual as b JOIN berkahgl_" . $unit . ".produksi as c on c.id_farm = a.id_farm and c.id_produksi = b.id_produksi where a.id_farm ='$id_farm' AND c.id_produksi ='$id_produksi' and b.id_barang LIKE 'F-%') as pakan,(SELECT DISTINCT SUM(b.qty) AS pakan FROM berkahgl_" . $unit . ".farm as a JOIN berkahgl_" . $unit . ".jual as b JOIN berkahgl_" . $unit . ".produksi as c on c.id_farm = a.id_farm and c.id_produksi = b.id_produksi where a.id_farm ='$id_farm' AND c.id_produksi ='$id_produksi' and b.id_barang LIKE 'M-%')/b.qty as ovk FROM berkahgl_" . $unit . ".farm as a JOIN berkahgl_" . $unit . ".jual as b JOIN berkahgl_" . $unit . ".produksi as c on c.id_farm = a.id_farm and c.id_produksi = b.id_produksi where a.id_farm ='$id_farm' AND c.id_produksi ='$id_produksi' and b.id_barang LIKE 'D-%'";
    echo $sql;
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if ($result) {
        $st = "1";
    } else {
        $st = "0";
    }
    return $response->withJson(["status" => $st, "data" => $result,], 200);
});
$app->get("/standarAyam/", function (Request $request, Response $response) {
    $bw = $request->getQueryParam("bw");
    $sql = "SELECT a.umur, a.bw, a.fi,a.fcr,a.ep,a.mort,a.ip FROM berkahgl_portal.stdayam as a WHERE a.bw ='$bw'";
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if ($result) {
        $st = "1";
    } else {
        $st = "0";
    }
    return $response->withJson(["status" => $st, "data" => $result,], 200);
});

$app->get("/karyawan/jenisPakan", function (Request $request, Response $response) {
    $unit = $request->getQueryParam("unit");
    $sql  = "SELECT a.id_barang, a.nama FROM berkahgl_" . $unit . ".barang as a WHERE id_barang LIKE 'F-%'";
    echo $sql;
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    if ($result) {
        $st = "1";
    } else {
        $st = "0";
    }
    return $response->withJson(["status" => $st, "data" => $result,], 200);
});
$app->post("/karyawan/HealtIndex", function (Request $request, Response $response) {
    $post = $request->getParsedBody();

    $id_produksi = $post['id_produksi'];
    $tangal_input = date("Y-m-d");
    $id_checkpoint = $post['id_checkpoint'];
    $suhu = $post['suhu'];
    $kelembaban = $post['kelembaban'];
    $heat_index = $post['heat_index'];

    $sql2 = "SELECT a.id_hi from berkahgl_portal.heat_index as a WHERE a.tgl_input LIKE '$tangal_input%' and a.id_checkpoint='$id_checkpoint'";
    $stmt2 = $this->db->prepare($sql2);
    $stmt2->execute();
    $rs = $stmt2->fetchColumn();
    if ($rs > 0) {
        return $response->withJson(["status" => 2], 200);
    } else {
        $sql = "INSERT INTO berkahgl_portal.heat_index (`id_hi`, `id_produksi`, `tgl_input`, `id_checkpoint`, `suhu`, `kelembaban`, `heat_index`) VALUES (NULL, '$id_produksi', '$tangal_input', '$id_checkpoint', '$suhu', '$kelembaban', '$heat_index')";
        $stmt = $this->db->prepare($sql);
        $cek = $stmt->execute();
        if ($cek) {
            $st = "1";
            $data = "data berhasil diinputkan";
        } else {
            $st = "0";
            $data = "data gagal diinput";
        }
        return $response->withJson(["status" => $st, "data" => $data], 200);
    }
});

$app->post("/karyawan/inputkph", function (Request $request, Response $response) {
    $post = $request->getParsedBody();
    $id_produksi = $post['id_produksi'];
    $tangal_input = date("Y-m-d");
    $id_checkpoint = $post['id_checkpoint'];
    $umur = $post['umur'];
    $kematian = $post['kematian'];
    $pakan = $post['pakan'];

    $sql2 = "SELECT a.id_kph from berkahgl_portal.kematian_pakan_harian as a WHERE a.tgl_input LIKE '$tangal_input%' and a.id_checkpoint='$id_checkpoint'";
    $stmt2 = $this->db->prepare($sql2);
    $stmt2->execute();
    $rs = $stmt2->fetchColumn();
    if ($rs > 0) {
        return $response->withJson(["status" => 2], 200);
    } else {
        $sql = "INSERT INTO berkahgl_portal.kematian_pakan_harian (`id_kph`, `id_produksi`, `tgl_input`, `id_checkpoint`, `umur`, `kematian`, `pakan`) VALUES (NULL, '$id_produksi', '$tangal_input', '$id_checkpoint', '$umur', '$kematian', '$pakan')";
        $stmt = $this->db->prepare($sql);
        $cek = $stmt->execute();
        if ($cek) {
            $st = "1";
            $data = "data berhasil diinputkan";
        } else {
            $st = "0";
            $data = "data gagal diinput";
        }
        return $response->withJson(["status" => $st, "data" => $data], 200);
    }
});

$app->post("/karyawan/inputCheckPoint", function (Request $request, Response $response) {
    $tglInput = date("Y-m-d H:i:s");
    $tglInput2 = date("Y-m-d");
    $post = $request->getParsedBody();
    $tangal_chickin = $post["dateChickIn"];
    $id_produksi = $post["id_produksi"];
    $nik = $post["nik"];
    $bobotdoc = $post["bobot"];
    $populasi = $post["populasi"];
    $umur_kontrol = $post["umur"];
    $bb = $post["bw"];
    $mortalitas = $post["mort"];
    $pakan = $post["pakan"];
    $feed_intake = $post["fi"];
    $age = $post["age"];
    $agepoint = $post["agepoint"];
    $adg = $post["adg"];
    $adgpoint = $post["adgpoint"];
    $fcr = $post["fcr"];
    $ip = $post["ip"];
    $beef = $post["beef"];
    $ayam = $post["ayam"];
    /*$tangal_chickin = $request->getQueryParam("dateChickIn");
    $id_produksi = $request->getQueryParam("id_produksi");
    $nik = $request->getQueryParam("nik");
    $bobotdoc=$request->getQueryParam("bobot");
    $populasi = $request->getQueryParam("populasi");
    $umur_kontrol = $request->getQueryParam("umur");
    $bb = $request->getQueryParam("bw");
    $mortalitas = $request->getQueryParam("mort");
    $pakan = $request->getQueryParam("pakan");
    $feed_intake = $request->getQueryParam("fi");
    $age = $request->getQueryParam("age");
    $agepoint = $request->getQueryParam("agepoint");
    $adg = $request->getQueryParam("adg");
    $adgpoint = $request->getQueryParam("adgpoint");
    $fcr = $request->getQueryParam("fcr");
    $ip = $request->getQueryParam("ip");
    $beef = $request->getQueryParam("beef");
    $ayam = $request->getQueryParam("ayam");*/




    //echo $tglInput;   
    //echo $sql;
    $sql2 = "SELECT a.id_checkpoint FROM berkahgl_portal.checkpoint as a WHERE a.tanggal_input LIKE '$tglInput2%' AND a.id_produksi LIKE '$id_produksi' AND a.nik LIKE '$nik'";
    //echo $sql2;

    $stmt = $this->db->prepare($sql2);
    $stmt->execute();

    $result = $stmt->fetchColumn();
    if ($result > 0) {
        $stmt = $this->db->prepare($sql2);
        $stmt->execute();
        $rs = $stmt->fetchAll();
        return $response->withJson(["status" => "2", "data" => $rs], 200);
    } else {
        $sql = "INSERT INTO berkahgl_portal.checkpoint (`id_checkpoint`, `tanggal_input`, `tanggal_chickin`, `id_produksi`, `nik`, `bobotdoc`, `populasi`, `umur_kontrol`, `bb`, `mortalitas`, `pakan`, `feed_intake`, `age`, `agepoint`, `adg`, `adgpoint`, `fcr`, `ip`, `beef`, `ayam`, `kondisi_ayam`, `ket`, `foto`, `saran`) VALUES (null, '$tglInput', '$tangal_chickin', '$id_produksi', '$nik', '$bobotdoc', '$populasi', '$umur_kontrol', '$bb', '$mortalitas', '$pakan', '$feed_intake', '$age', '$agepoint', '$adg', '$adgpoint', '$fcr', '$ip', '$beef', '$ayam','0','0','0','0')";
        $stmt = $this->db->prepare($sql);
        $check = $stmt->execute();
        //$result = $stmt->fetchAll();
        if ($check) {
            $st = "1";
            $sql3 = "SELECT a.id_checkpoint  FROM berkahgl_portal.checkpoint as a WHERE a.tanggal_input LIKE '$tglInput2%' AND a.id_produksi LIKE '$id_produksi' AND a.nik LIKE '$nik'";
            $stmt2 = $this->db->prepare($sql3);
            $stmt2->execute();
            $result2 = $stmt2->fetchAll();
        } else {
            $st = "0";
        }
        return $response->withJson(["status" => $st, "data" => $result2], 200);
    }
    // echo $stmt;

    /* $sql = "INSERT INTO berkahgl_portal.checkpoint (`id_checkpoint`, `tanggal_input`, `tanggal_chickin`, `id_produksi`, `nik`, `bobotdoc`, `populasi`, `umur_kontrol`, `bb`, `mortalitas`, `pakan`, `feed_intake`, `age`, `agepoint`, `adg`, `adgpoint`, `fcr`, `ip`, `beef`, `ayam`) VALUES (null, '$tglInput', '$tangal_chickin', '$id_produksi', '$nik', '$bobotdoc', '$populasi', '$umur_kontrol', '$bb', '$mortalitas', '$pakan', '$feed_intake', '$age', '$agepoint', '$adg', '$adgpoint', '$fcr', '$ip', '$beef', '$ayam')";
        $stmt = $this->db->prepare($sql);*/
});
$app->post("/karyawan/obat", function (Request $request, Response $response) {
    $post = $request->getParsedBody();
    $id_produksi = $post['id_produksi'];
    $tangal_input = date("Y-m-d");
    $id_checkpoint = $post['id_checkpoint'];
    $umur = $post['umur'];
    $pagi = $post['pagi'];
    $sore = $post['sore'];

    $sql2 = "SELECT a.id_pemakaian from berkahgl_portal.pemakaian_obat as a WHERE a.tgl_input LIKE '$tangal_input%' and a.id_checkpoint='$id_checkpoint'";
    $stmt2 = $this->db->prepare($sql2);
    $stmt2->execute();
    $rs = $stmt2->fetchColumn();
    if ($rs > 0) {
        return $response->withJson(["status" => '2'], 200);
    } else {
        $sql = "INSERT INTO berkahgl_portal.pemakaian_obat (`id_pemakaian`, `id_produksi`, `tgl_input`, `id_checkpoint`, `umur`, `pagi`, `sore`) VALUES (NULL, '$id_produksi', '$tangal_input', '$id_checkpoint', '$umur', '$pagi', '$sore')";
        $stmt = $this->db->prepare($sql);
        $cek = $stmt->execute();
        if ($cek) {
            $st = "1";
            $data = "data berhasil diinputkan";
        } else {
            $st = "0";
            $data = "data gagal diinput";
        }
        return $response->withJson(["status" => $st, "data" => $data], 200);
    }
});

$app->post('/books/cover/', function (Request $request, Response $response, $args) {

    $uploadedFiles = $request->getUploadedFiles();

    // handle single input with single file upload
    $uploadedFile = $uploadedFiles['cover'];
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {

        /** PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME
         */
        $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
        $dirname = pathinfo($uploadedFile->getClientFilename(), PATHINFO_DIRNAME);
        $basename = pathinfo($uploadedFile->getClientFilename(), PATHINFO_BASENAME);
        $filename = pathinfo($uploadedFile->getClientFilename(), PATHINFO_FILENAME);
        $size = $uploadedFile->getSize();
        echo "extension " . $extension . "<br>";
        echo "dir name " . $dirname . "<br>";
        echo "base name " . $basename . "<br>";
        echo "file name " . $filename . "<br>";
        echo "size " . $size . "<br>";
        // ubah nama file dengan id buku
        $filename = sprintf('%s.%0.8s', "", $extension);
        echo " file name " . $filename;
        $directory = $this->get('settings')['upload_directory'];
        echo " dir  " . $directory;
        //$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);

        /*// simpan nama file ke database
        $sql = "UPDATE books SET cover=:cover WHERE book_id=:id";
        $stmt = $this->db->prepare($sql);
        $params = [
            ":id" => $args["id"],
            ":cover" => $filename
        ];
        
        if($stmt->execute($params)){
            // ambil base url dan gabungkan dengan file name untuk membentuk URL file
            $url = $request->getUri()->getBaseUrl()."/uploads/".$filename;
            return $response->withJson(["status" => "success", "data" => $url], 200);
        }*/

        return $response->withJson(["status" => "failed", "data" => "0"], 200);
    }
});

$app->post("/karyawan/kondisiAyam", function (Request $request, Response $response) {
    $post = $request->getParsedBody();

    $id_produksi = $post['id_produksi'];
    $tangal_input = date("Y-m-d");
    $id_checkpoint = $post['id_checkpoint'];
    $ket = $post['ket'];
    $saran = $post['saran'];
    $kondisi = $post['kondisi'];
    $sql = "UPDATE berkahgl_portal.checkpoint SET `ket` = '$ket', `foto` = '1', `saran` = '$saran', kondisi_ayam='$kondisi' WHERE `checkpoint`.`id_checkpoint` = $id_checkpoint";
    $stmt = $this->db->prepare($sql);
    $cek = $stmt->execute();
    if ($cek) {
        $st = "1";
        $data = "data berhasil diinputkan";
    } else {
        $st = "0";
        $data = "data gagal diinput";
    }
    return $response->withJson(["status" => $st, "data" => $data], 200);
});

# ===================================
# ====== API ANDROID BERKAH GO ======
# ===================================


$app->post("/login", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {

        //$db = $this->db;
        $userData = '';
        $sql = "SELECT nik, hak_akses FROM login WHERE username=:username AND password=:password ";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam("username", $data->username, PDO::PARAM_STR);
        $password = md5($data->password);
        $stmt->bindParam("password", $password, PDO::PARAM_STR);
        $stmt->execute();
        $mainCount = $stmt->rowCount();
        $userData = $stmt->fetch(PDO::FETCH_OBJ);

        if (!empty($userData)) {
            $user_id = $userData->user_id;
            $userData->token = apiToken($user_id);
        }

        //$db = null;
        if ($userData) {
            $userData = json_encode($userData);
            echo '{"userData": ' . $userData . '}';
        } else {
            echo '{"error":{"text":"Bad request wrong username and password"}}';
        }
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel jurnal
$app->get("/jurnal/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $data_request = $request->getParams();

    try {
        $query_where = '';

        # hapus param key
        # hapus param dari_tanggal sampai_tgl karena akan di input manual
        unset($data_request['nik']);
        unset($data_request['dari_tgl']);
        unset($data_request['sampai_tgl']);
        unset($data_request['keterangan']);
        if ($data_request['unit'] === '') {
            unset($data_request['unit']);
        }
        if ($data_request['approve_drt'] === '') {
            unset($data_request['approve_drt']);
        }

        # buat query where dari request yang dikirim
        foreach ($data_request as $key => $value) {
            $query_where .= " AND a." . $key . " = '" . $value . "'";
        }

        # masukan jika ada param dari_tgl
        if ($request->getQueryParam("dari_tgl")) {
            $query_where .= " AND a.tgl >= '" . $request->getQueryParam("dari_tgl") . "'";
        }
        # masukan jika ada param sampai_tgl
        if ($request->getQueryParam("sampai_tgl")) {
            $query_where .= " AND a.tgl <= '" . $request->getQueryParam("sampai_tgl") . "'";
        }
        # masukan jika ada param sampai_tgl
        if ($request->getQueryParam("keterangan")) {
            $query_where .= " AND a.uraian1 like '%" . $request->getQueryParam("keterangan") . "%'";
        }
        # haus string AND pertama di query
        $query_where = substr($query_where, 4);

        $sql = "SELECT a.no_transaksi, a.tgl, a.uraian1 AS keterangan, IF(a.debet1 != 0, 'debit', 'kredit') AS proses, IF(a.debet1 != 0, 'success', 'danger') AS colorProses, IF(a.debet1 != 0, a.debet1, a.kredit1) AS nilai, b.nama_akun AS akun1, c.nama_akun AS akun2, a.unit, 'false' AS isChecked
            FROM jurnal a 
            JOIN akun b ON a.akun1=b.id_akun JOIN akun c ON a.akun2=c.id_akun 
            WHERE " . $query_where . " AND ( a.unit='bgt' || a.unit='bmm' || a.unit='bsm1' || a.unit='bsm2' || a.unit='koperasi' || a.unit='rnd' || a.unit='trd' ) AND (a.uraian1 NOT LIKE 'Penjualan barang%' AND a.uraian1 NOT LIKE 'Pembelian barang kepada %') AND a.tgl != '0000-00-00' ORDER BY a.tgl DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel jurnal_mgt
$app->get("/jurnal_mgt/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $data_request = $request->getParams();

    try {
        $query_where = '';

        # hapus param key
        # hapus param dari_tanggal sampai_tgl karena akan di input manual
        unset($data_request['nik']);
        unset($data_request['dari_tgl']);
        unset($data_request['sampai_tgl']);
        unset($data_request['keterangan']);
        if ($data_request['app_drt'] === '') {
            unset($data_request['app_drt']);
        }

        # buat query where dari request yang dikirim
        foreach ($data_request as $key => $value) {
            $query_where .= " AND a." . $key . " = '" . $value . "'";
        }

        # masukan jika ada param dari_tgl
        if ($request->getQueryParam("dari_tgl")) {
            $query_where .= " AND a.tgl >= '" . $request->getQueryParam("dari_tgl") . "'";
        }
        # masukan jika ada param sampai_tgl
        if ($request->getQueryParam("sampai_tgl")) {
            $query_where .= " AND a.tgl <= '" . $request->getQueryParam("sampai_tgl") . "'";
        }

        # masukan jika ada param sampai_tgl
        if ($request->getQueryParam("keterangan")) {
            $query_where .= " AND a.uraian1 like '%" . $request->getQueryParam("keterangan") . "%'";
        }

        # haus string AND pertama di query
        $query_where = substr($query_where, 4);

        $sql = "SELECT a.no_transaksi, a.tgl, a.uraian1 AS keterangan, IF(a.debet1 != 0, 'debit', 'kredit') AS proses, IF(a.debet1 != 0, 'success', 'danger') AS colorProses, IF(a.debet1 != 0, a.debet1, a.kredit1) AS nilai, b.nama_akun AS akun1, c.nama_akun AS akun2, 'false' AS isChecked
            FROM jurnal_mgt a 
            JOIN akun b ON a.akun1=b.id_akun JOIN akun c ON a.akun2=c.id_akun 
            WHERE " . $query_where . " AND a.tgl != '0000-00-00' ORDER BY a.tgl DESC ";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel jurnal_mgt
$app->get("/transfer_do/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $data_request = $request->getParams();

    try {

        $result = getPengajuanTransferDO($data_request['dari_tanggal'], $data_request['sampai_tanggal'], $data_request['jenis']);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

$app->post("/transfer_do/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $kode_transfer = $data->kode_transfer;

        $result = approveTransferDO($kode_transfer, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

$app->post("/jurnal/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;

        $sql = "UPDATE jurnal SET approve_drt=:approve_drt WHERE no_transaksi=:no_transaksi";
        $stmt = $this->db->prepare($sql);

        foreach ($data->no_transaksi as $key => $no_transaksi) {

            $row = [
                ":no_transaksi" => $no_transaksi,
                ":approve_drt"  => $approve_drt
            ];

            $stmt->execute($row);
        }

        if ($stmt->rowCount() > 0) {
            return $response->withJson(["status" => "success", "data" => "1"], 200);
        } else {
            return $response->withJson(["status" => "failed", "data" => "0"], 200);
        }
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});


$app->post("/jurnal_mgt/approve_drt", function (Request $request, Response $response, $args) {
    $data = json_decode($request->getBody());
    try {

        $approve_drt = $data->approve_drt;

        $sql = "UPDATE jurnal_mgt SET app_drt=:approve_drt WHERE no_transaksi=:no_transaksi";
        $stmt = $this->db->prepare($sql);

        foreach ($data->no_transaksi as $key => $no_transaksi) {

            $row = [
                ":no_transaksi" => $no_transaksi,
                ":approve_drt"  => $approve_drt
            ];

            $stmt->execute($row);
        }

        if ($stmt->rowCount() > 0) {
            return $response->withJson(["status" => "success", "data" => "1"], 200);
        } else {
            return $response->withJson(["status" => "failed", "data" => "0"], 200);
        }
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

$app->get("/jurnal/unit", function (Request $request, Response $response, $args) {

    $data[0]['id'] = 'bgt';
    $data[0]['name'] = 'BGT';
    $data[1]['id'] = 'bmm';
    $data[1]['name'] = 'BMM';
    $data[2]['id'] = 'bsm1';
    $data[2]['name'] = 'BSM1';
    $data[3]['id'] = 'bsm2';
    $data[3]['name'] = 'BSM2';
    $data[4]['id'] = 'koperasi';
    $data[4]['name'] = 'KOPERASI';
    $data[5]['id'] = 'rnd';
    $data[5]['name'] = 'RND';
    $data[6]['id'] = 'trd';
    $data[6]['name'] = 'TRD';
    $data[7]["id"] = "DBC";
    $data[7]["name"] = "dapur";
    $data[8]["id"] = "BBD";
    $data[8]["name"] = "BCO Bandung";
    $data[9]["id"] = "BBG";
    $data[9]["name"] = "BCO Bogor";
    $data[10]["id"] = "BCR";
    $data[10]["name"] = "BCO Cirebon";
    $data[11]["id"] = "BDP";
    $data[11]["name"] = "BCO Depok";
    $data[12]["id"] = "BJK";
    $data[12]["name"] = "BCO Jakarta";
    $data[13]["id"] = "BKN";
    $data[13]["name"] = "BCO Kuningan";
    $data[14]["id"] = "BPW";
    $data[14]["name"] = "BCO Purwokerto";
    $data[15]["id"] = "BSG";
    $data[15]["name"] = "BCO Semarang";
    $data[16]["id"] = "BTS";
    $data[16]["name"] = "BCO Tasikmalaya";


    return $response->withJson(["status" => "success", "data" => $data], 200);
});


# get data tabel farrm masih proses DRT
$app->get("/farm/proses_app_drt", function (Request $request, Response $response, $args) {

    try {

        $sql = "SELECT a.id, a.unit, a.nama, a.desa_peternak, a.kec_peternak, a.kota_peternak, a.desa, a.kec, a.kota, a.populasi, a.lokasi, a.sistem_kandang, 'false' AS isChecked,
            (SELECT tindakan FROM tindakan WHERE id_produksi LIKE CONCAT(a.id, '%') ORDER BY id_tindakan DESC LIMIT 1 ) AS alasan_pusat_approve 
            FROM farm a
            WHERE a.app_drt='Proses' AND a.app_pusat='Approve' AND a.app_manager='Approve' AND a.app_ts='Approve' ORDER BY a.id ASC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel farrm bredasarkan id
$app->get("/farm/id", function (Request $request, Response $response, $args) {
    # ambil data request url
    $data_request = $request->getParams();

    try {

        $sql = "SELECT a.*, 
            (SELECT tindakan FROM tindakan WHERE id_produksi LIKE CONCAT(a.id, '%') ORDER BY id_tindakan DESC LIMIT 1 ) AS alasan_pusat_approve
            FROM farm a
            WHERE a.id='$data_request[id]' ";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        //    $result = json_encode($result);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});


$app->post("/farm/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $ids = $data->ids;

        $result = approveFarmBaru($ids, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel pengajuan farm-off masih proses DRT
$app->get("/farm-off/proses_app_drt", function (Request $request, Response $response, $args) {

    try {

        $sql = "SELECT idupdate, id_farm, nama, alasan, unit, tanggal, 'false' AS isChecked
            FROM update_ts
            WHERE ket='Approve' AND app_man='Approve' AND app_drt='Proses' ORDER BY tanggal ASC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel farm-off bredasarkan id
$app->get("/farm-off/id", function (Request $request, Response $response, $args) {
    # ambil data request url
    $data_request = $request->getParams();

    try {

        $result = getPengajuanFarmOff($data_request['idupdate']);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});


$app->post("/farm-off/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $ids = $data->ids;

        $result = approveFarmOff($ids, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});



# get data tabel ajuan_rak_unit
$app->get("/ajuan_rak_unit/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $app_drt = $request->getQueryParam("app_drt");
    $limit = $request->getQueryParam("limit");
    $keyword = $request->getQueryParam("keyword");

    if ($limit != '') {
        $limitRows = " LIMIT " . $limit;
    } else {
        $limitRows = '';
    }

    try {

        $sql = "SELECT a.*, unit1.nama_unit AS nama_unit_asal, unit2.nama_unit AS nama_unit_tujuan, 'false' AS isChecked
            FROM ajuan_rak_unit a
            JOIN unit AS unit1 ON a.unit_asal=unit1.id_unit JOIN unit AS unit2 ON a.unit_tujuan=unit2.id_unit 
            WHERE a.app_unit='Approve' AND a.app_drt='$app_drt'
            AND ( a.nominal LIKE '%$keyword%' OR a.alasan LIKE '%$keyword%' )
            ORDER BY a.tgl_pengajuan DESC 
            $limitRows ";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});


$app->post("/ajuan_rak_unit/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $ids = $data->ids;

        $result = approveRAKunit($ids, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

# get data tabel ajuan_bayar_bgt
$app->get("/ajuan_bayar_bgt/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $app_drt = $request->getQueryParam("app_drt");
    $limit = $request->getQueryParam("limit");
    $keyword = $request->getQueryParam("keyword");

    if ($limit != '') {
        $limitRows = " LIMIT " . $limit;
    } else {
        $limitRows = '';
    }

    try {

        $sql = "SELECT a.*, akun.nama_akun, 'false' AS isChecked
            FROM ajuan_bayar_bgt a
            JOIN akun ON a.sistem=akun.id_akun
            WHERE a.app_unit='Approve' AND a.app_drt='$app_drt' 
            AND ( a.nominal LIKE '%$keyword%' OR a.command LIKE '%$keyword%' )
            ORDER BY a.tgl_pengajuan DESC 
            $limitRows ";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

$app->post("/ajuan_bayar_bgt/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $ids = $data->ids;

        $result = approveBayarBGT($ids, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

#coba
$app->post("/coba_link/",function(Request $request, Response $response,$args){
    return $response->withJson(["status" => "success", "data" =>"dad"], 200);
});


# get data tabel ajuan_bahan_bakar
$app->get("/ajuan_bahan_bakar/", function (Request $request, Response $response, $args) {

    # ambil data request url
    $app_drt = $request->getQueryParam("app_drt");
    $limit = $request->getQueryParam("limit");
    $keyword = $request->getQueryParam("keyword");

    if ($limit != '') {
        $limitRows = " LIMIT " . $limit;
    } else {
        $limitRows = '';
    }

    try {

        $sql = "SELECT a.*, unit1.nama_unit AS nama_unit_asal, unit2.nama_unit AS nama_unit_tujuan, 'false' AS isChecked
            FROM ajuan_bahan_bakar a
            JOIN unit AS unit1 ON a.unit_asal=unit1.id_unit JOIN unit AS unit2 ON a.unit_tujuan=unit2.id_unit 
            WHERE a.app_unit='Approve' AND a.app_drt='$app_drt' 
            AND ( a.command LIKE '%$keyword%' )
            ORDER BY a.tgl_pengajuan DESC 
            $limitRows ";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response->withJson(["status" => "success", "data" => $result], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

$app->post("/ajuan_bahan_bakar/approve_drt", function (Request $request, Response $response, $args) {

    $data = json_decode($request->getBody());

    try {
        $approve_drt = $data->approve_drt;
        $ids = $data->ids;

        $result = approveBaharBakar($ids, $approve_drt);

        return $response->withJson(["status" => $result['status'], "data" => $result['data']], 200);
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});

// $app->get("/farms/", function (Request $request, Response $response){
//     $sql = "SELECT * FROM farm";
//     $stmt = $this->db->prepare($sql);
//     $result = $stmt->fetchAll();
//     return $response->withJson(["status" => "success", "data" => $result], 200);
// });

// $app->get("/farms/{id}", function (Request $request, Response $response, $args){
//     $id = $args["id"];
//     $sql = "SELECT * FROM farm WHERE id=:id";
//     $stmt = $this->db->prepare($sql);
//     $stmt->execute([":id" => $id]);
//     $result = $stmt->fetch();
//     return $response->withJson(["status" => "success", "data" => $result], 200);
// });

// $app->get("/books/search/", function (Request $request, Response $response, $args){
//     $keyword = $request->getQueryParam("keyword");
//     $sql = "SELECT * FROM books WHERE title LIKE '%$keyword%' OR sinopsis LIKE '%$keyword%' OR author LIKE '%$keyword%'";
//     $stmt = $this->db->prepare($sql);
//     $stmt->execute();
//     $result = $stmt->fetchAll();
//     return $response->withJson(["status" => "success", "data" => $result], 200);
// });

// $app->post("/books/", function (Request $request, Response $response){

//     $new_book = $request->getParsedBody();

//     $sql = "INSERT INTO books (title, author, sinopsis) VALUE (:title, :author, :sinopsis)";
//     $stmt = $this->db->prepare($sql);

//     $data = [
//         ":title" => $new_book["title"],
//         ":author" => $new_book["author"],
//         ":sinopsis" => $new_book["sinopsis"]
//     ];

//     if($stmt->execute($data))
//        return $response->withJson(["status" => "success", "data" => "1"], 200);
    
//     return $response->withJson(["status" => "failed", "data" => "0"], 200);
// });

// $app->put("/books/{id}", function (Request $request, Response $response, $args){
//     $id = $args["id"];
//     $new_book = $request->getParsedBody();
//     $sql = "UPDATE books SET title=:title, author=:author, sinopsis=:sinopsis WHERE book_id=:id";
//     $stmt = $this->db->prepare($sql);
    
//     $data = [
//         ":id" => $id,
//         ":title" => $new_book["title"],
//         ":author" => $new_book["author"],
//         ":sinopsis" => $new_book["sinopsis"]
//     ];

//     if($stmt->execute($data))
//        return $response->withJson(["status" => "success", "data" => "1"], 200);
    
//     return $response->withJson(["status" => "failed", "data" => "0"], 200);
// });

// $app->delete("/books/{id}", function (Request $request, Response $response, $args){
//     $id = $args["id"];
//     $sql = "DELETE FROM books WHERE book_id=:id";
//     $stmt = $this->db->prepare($sql);
    
//     $data = [
//         ":id" => $id
//     ];

//     if($stmt->execute($data))
//        return $response->withJson(["status" => "success", "data" => "1"], 200);
    
//     return $response->withJson(["status" => "failed", "data" => "0"], 200);
// });
