<?php
// Aktifkan pelaporan kesalahan untuk pengembangan
error_reporting(E_ALL);
ini_set('display_errors', 1); // Menampilkan kesalahan untuk pengembangan

function sanitizeString($input) {
    $str01 = preg_replace('/[^a-zA-Z0-9\s]/', ' ', $input);
    $str02 = preg_replace('/\s+/', ' ', $str01);
    $str03 = trim($str02); // Perbaiki penamaan variabel di sini
    return $str03;
}

include "../config/connect.php";

try {
    $sqlData = "SELECT id, apikey_payment_gateway,url_payment_gateway FROM data_server WHERE status_payment_gateway = 'ACTIVE' AND apikey_payment_gateway != '' AND tokenkey_payment_gateway != '' AND url_payment_gateway != ''";
    $stmtData = $pdo->query($sqlData);

    while ($dataambil = $stmtData->fetch(PDO::FETCH_ASSOC)) {
        $idds = $dataambil['id'];

        $apiKey = $dataambil['apikey_payment_gateway'];
        $apiUrl = $dataambil['url_payment_gateway'];

        $sqlProfil = "SELECT id, kirim_tagihan FROM profile_tagihan WHERE id_data_server = :id_data_server";
        $stmtProfil = $pdo->prepare($sqlProfil);
        $stmtProfil->bindParam(':id_data_server', $idds, PDO::PARAM_INT);
        $stmtProfil->execute();

        while ($dataprofil = $stmtProfil->fetch(PDO::FETCH_ASSOC)) {
            $sql = "SELECT * FROM v_tagihan WHERE id_data_server = :idds AND id_profile_tagihan = :idpt AND status = 'buat' AND transaction_id IS NULL AND transaction_link IS NULL AND transaction_status IS NULL AND verifikasi_tagihan > 1000 AND RIGHT(email, 10) = '@gmail.com'";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':idds' => $idds, ':idpt' => $dataprofil['id']]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);
            echo $dataprofil['id'];
            // Pastikan $data['limit_pembayaran'] ada dan tidak kosong
            if ($data && isset($data['limit_pembayaran'])) {
                $day = str_pad($dataprofil['kirim_tagihan'], 2, '0', STR_PAD_LEFT);
                $cekkirim = substr($data['limit_pembayaran'], 0, 8) . $day;

                // Pastikan format tanggal valid
                try {
                    $date = new DateTime($cekkirim);
                    $date->modify('-1 day');
                    $cektanggal = $date->format('Y-m-d');
                    $sekarang = date('Y-m-d');

                    if ($sekarang == $cektanggal) {
                        // Kode untuk meng-create link payment gateway
                        require '../payment/flip/Flip/Transaction.php';
                        $flip = new FlipPaymentGateway($apiKey, $apiUrl);

                        $response = $flip->createBill(
                            sanitizeString($data['keterangan']),
                            sanitizeString($data['verifikasi_tagihan']),
                            $data['email'],
                            sanitizeString($data['nama']),
                            sanitizeString($data['nomor_whatsapp']),
                            sanitizeString($data['alamat'])
                        );

                        if (!empty($response['link_id']) && !empty($response['link_url']) && !empty($response['status'])) { 
                            $transaction_id = $response['link_id'];
                            $transaction_link = $response['link_url'];
                            $transaction_status = $response['status'];

                            $stmt = $pdo->prepare("UPDATE tagihan SET transaction_id = :transaction_id, transaction_link = :transaction_link, transaction_status = :transaction_status WHERE id = :idtag");
                            $stmt->bindParam(':transaction_id', $transaction_id);
                            $stmt->bindParam(':transaction_link', $transaction_link);
                            $stmt->bindParam(':transaction_status', $transaction_status);
                            $stmt->bindParam(':idtag', $data['id']);
                            $stmt->execute();
                            echo " =>Success ".$data['nama'].", SV :".$data['nama_server'];
                        } else {
                            echo " =>Error ".$data['nama'].", SV :".$data['nama_server'];
                            print_r($response);
                        }
                    } else {
                        echo "No Data";
                    }
                } catch (Exception $e) {
                    echo "Tanggal tidak valid: " . $e->getMessage();
                }
            } else {
                echo "Data tidak ditemukan";
            }
        }
    }
} catch (PDOException $e) {
    error_log('Database Error: ' . $e->getMessage());
    echo "Database error occurred: " . $e->getMessage();
} catch (Exception $e) {
    error_log('General Error: ' . $e->getMessage());
    echo "An error occurred: " . $e->getMessage();
}
?>
