<?php

require_once "../config.php";

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

date_default_timezone_set('Asia/Jakarta');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

switch ($method) {

    case 'POST':

        $data = json_decode(file_get_contents("php://input"), true);

        $cKodeMember = isset($data['cKodeMember']) ? $data['cKodeMember'] : '';
        $cKet = isset($data['cKet']) ? $data['cKet'] : '';
        $nTerm = isset($data['nTerm']) ? $data['nTerm'] : null;
        $cKota = isset($data['cKota']) ? $data['cKota'] : '';
        $cjenisbayar = isset($data['cjenisbayar']) ? $data['cjenisbayar'] : '';
        $diskon4 = isset($data['diskon4']) ? $data['diskon4'] : 0;
        $alamatku = isset($data['alamatku']) ? $data['alamatku'] : '';
        $bayarmidtrans = $data['bayarmidtrans'];
        $totalmidtrans = preg_replace('/[^0-9]/', '', $data['totalmidtrans']);
        $cnoid         = '001';

        $today = date("ymd");

        $query  = "SELECT cNoSo FROM tbSODtl WHERE cNoSo LIKE 'SOA-$today%' ORDER BY cNoSo DESC LIMIT 1";
        $result = $conn->query($query);

        if ($result && $result->num_rows > 0) {
            $lastNoSo = $result->fetch_assoc()['cNoSo'];
            $lastNo   = substr($lastNoSo, -3);
            $newNo    = str_pad($lastNo + 1, 3, '0', STR_PAD_LEFT);
        } else {
            $newNo = '001';
        }

        $newNoSo = 'SOA-' . $today . $newNo;

        $queryMember = "SELECT * FROM tbmember WHERE cKodeCust = ?";
        $stmtMember  = $conn->prepare($queryMember);
        $stmtMember->bind_param("s", $cKodeMember);
        $stmtMember->execute();
        $memberResult = $stmtMember->get_result();

        if ($memberResult->num_rows > 0) {

            $memberData = $memberResult->fetch_assoc();

            $cemail       = (!empty($memberData['cemail'])) ? $memberData['cemail'] : 'ayam@gmail.com';
            $cpassword    = $memberData['cpassword'];
            $cnama        = $memberData['cnama'];
            $cnohp        = $memberData['cnohp'];
            $dtgllahir    = $memberData['dtgllahir'];
            $ckelamin     = $memberData['ckelamin'];
            $calamat      = $memberData['calamat'];
            $ckota        = $memberData['ckota'];
            $ckodecust    = $memberData['ckodecust'];
            $cVersi       = $memberData['cVersi'];
            $lAmbil       = $memberData['lAmbil'];
            $cJenisMember = $memberData['cJenisMember'];
            $carea        = $memberData['carea'];
            $ckodepl      = $memberData['ckodepl'];
            $ndisccash    = $memberData['ndisccash'];

            $queryCheck = "SELECT 1 FROM tbkeranjang WHERE cKodeMember = ? LIMIT 1";
            $stmtCheck  = $conn->prepare($queryCheck);
            $stmtCheck->bind_param("s", $cKodeMember);
            $stmtCheck->execute();
            $checkResult = $stmtCheck->get_result();

            if ($checkResult->num_rows === 0) {
                echo json_encode([]);
                exit();
            }

            if ($cjenisbayar === 'C') {
                $queryUpdateDiskon = "
                    UPDATE tbkeranjang
                    SET 
                        nDisc4 = ?,
                        nSTotal = ROUND(
                            nHarga * nQty
                            * (1 - nDisc1 / 100)
                            * (1 - nDisc2 / 100)
                            * (1 - nDisc3 / 100)
                            * (1 - ? / 100), 2
                        )
                    WHERE cKodeMember = ?
                ";
                $stmtUpdate = $conn->prepare($queryUpdateDiskon);
                $stmtUpdate->bind_param("dds", $diskon4, $diskon4, $cKodeMember);
                $stmtUpdate->execute();
                $stmtUpdate->close();
            }

            $queryTotal = "
                SELECT 
                    SUM(nSTotal) AS totalSTotal,
                    SUM(nSTotal) AS totalGTotal
                FROM tbkeranjang
                WHERE cKodeMember = ?
            ";
            $stmtTotal = $conn->prepare($queryTotal);
            $stmtTotal->bind_param("s", $cKodeMember);
            $stmtTotal->execute();
            $totalResult = $stmtTotal->get_result()->fetch_assoc();

            $nSTotal = $totalResult['totalSTotal'];
            $nGTotal = $totalResult['totalGTotal'];

            $queryInsert = "
                INSERT INTO tbSODtl (
                    cNoSo, cNoid, cKodeBrg, cNama, nQty1, nIsi, cSat, nQty2, lnStock,
                    cSat2, nTotQty, cSat3, nIsi2, nQty3, nIsi3, nQty4, cSat4,
                    cSat5, nIsi4, cHal, cNoDtl, cmerek, cspesifikasi, nharga,
                    nStotal, nDisc, nDisc2, nDisc3, nDisc4, nCol, nDiscPersen
                )
                SELECT
                    ?,
                    t.cNoID,
                    t.cKodeBrg,
                    t.cNamaBrg,
                    t.nQty,
                    1,
                    t.cSat,
                    0,
                    0,
                    '',
                    0,
                    '',
                    0,
                    0,
                    0,
                    0,
                    '',
                    '',
                    0,
                    '',
                    t.ID,
                    '',
                    'Spesifikasi',
                    t.nHarga,
                    t.nSTotal,
                    t.nDisc1,
                    t.nDisc2,
                    t.nDisc3,
                    t.nDisc4,
                    0,
                    0
                FROM tbkeranjang t
                JOIN tbbarang b ON t.cKodeBrg = b.cKode
                WHERE t.cKodeMember = ?
                ON DUPLICATE KEY UPDATE
                    nQty1   = VALUES(nQty1),
                    nHarga  = VALUES(nHarga),
                    nStotal = VALUES(nStotal)
            ";

            $stmtInsert = $conn->prepare($queryInsert);
            $stmtInsert->bind_param("ss", $newNoSo, $cKodeMember);
            $stmtInsert->execute();
            $stmtInsert->close();

            $queryCourier = "
                SELECT 
                    cjnskurir, cnamakurir, ckodekurir, cservicekurir,
                    cdescriptionkurir, ccostkurir, cetdkurir
                FROM tbkeranjang
                WHERE cKodeMember = ?
                LIMIT 1
            ";
            $stmtCourier = $conn->prepare($queryCourier);
            $stmtCourier->bind_param("s", $cKodeMember);
            $stmtCourier->execute();
            $courierData = $stmtCourier->get_result()->fetch_assoc();

            $cleanedCost = (float) str_replace(['Rp', '.', ' '], '', $courierData['ccostkurir']);

            $querySO = "
                INSERT INTO tbSO (
                    cNoSO, dtanggal, cKode, cNamaCust, cKota, nTerm, cKet,
                    lPosted, lVoid, dTglBtlPost, dTglVoid, UserId, UserDate,
                    nSTotal, nGTotal, cAlamat1, carea, lStock,
                    cKodeSales, cHal, cKodePl, cjenisbayar, cDiscList,
                    cjnskurir, cnamakurir, ckodekurir, cservicekurir,
                    cdescriptionkurir, ccostkurir, cetdkurir, nnongkos
                )
                VALUES (
                    ?, CURDATE(), ?, ?, ?, ?, ?, 0, 0,
                    '1900-01-01 00:00:00', '1900-01-01 00:00:00',
                    ?, NOW(), ?, ?, ?, '', 0, '', 0, 0,
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                )
            ";

            $stmtSO = $conn->prepare($querySO);
            $stmtSO->bind_param(
                "ssssssssssssssssssss",
                $newNoSo,
                $cKodeMember,
                $cnama,
                $cKota,
                $nTerm,
                $cKet,
                $cnama,
                $nSTotal,
                $nGTotal,
                $alamatku,
                $cjenisbayar,
                $ndisccash,
                $courierData['cjnskurir'],
                $courierData['cnamakurir'],
                $courierData['ckodekurir'],
                $courierData['cservicekurir'],
                $courierData['cdescriptionkurir'],
                $courierData['ccostkurir'],
                $courierData['cetdkurir'],
                $cleanedCost
            );
            $stmtSO->execute();
            $stmtSO->close();

            /* ====== STOCK APLIKASI ====== */

            $queryStockApp = "
                INSERT INTO tbstockaplikasi (
                    cnomer, dtanggal, ckode, cnama, ckodebrg, cnamabrg,
                    cnoid, cpos, nqty, csat, nisi, ntotqty, ntotqtyreal,
                    nhrgjual, ntotal, cid
                )
                SELECT
                    ?, CURDATE(), ?, ?, t.cKodeBrg, b.cNama,
                    t.cNoID, '', -t.nQty, t.cSat, 1,
                    -t.nQty, -t.nQty, t.nHarga, t.nSTotal, ''
                FROM tbkeranjang t
                JOIN tbbarang b ON t.cKodeBrg = b.cKode
                WHERE t.cKodeMember = ?
            ";

            $stmtStockApp = $conn->prepare($queryStockApp);
            $stmtStockApp->bind_param("ssss", $newNoSo, $cKodeMember, $cnama, $cKodeMember);
            $stmtStockApp->execute();
            $stmtStockApp->close();

            /* ====== PAYMENT MIDTRANS ====== */

            $queryPayment = "
                SELECT ckode, cpayment, clink, cwaktu
                FROM tbjnspayment
                WHERE ckode = ?
            ";
            $stmtPayment = $conn->prepare($queryPayment);
            $stmtPayment->bind_param("s", $bayarmidtrans);
            $stmtPayment->execute();
            $paymentData = $stmtPayment->get_result()->fetch_assoc();
            $stmtPayment->close();

            $datetime = new DateTime();
            $datetime->modify("+" . $paymentData['cwaktu'] . " minutes");
            $expired_at = $datetime->format('Y-m-d H:i:s');

            $orderayam = $newNoSo . time();



            $paymentUrl = '';
            
            

            $queryPiutang = "
                INSERT INTO tbpiutang (
                    cnomer, dtanggal, cid, cnoorder, ckdcust, cnmcust,
                    dtglorder, etglexpired, nnominal, cnoid,
                    clinkpembayaran, cstatuspembayaran, cjnsbiaya, cnamabiaya
                )
                VALUES (
                    ?, CURDATE(), 'A', ?, ?, ?, CURDATE(), ?, ?, ?, ?, 'pending', ?, ?
                )
            ";

            $stmtPiutang = $conn->prepare($queryPiutang);
            $stmtPiutang->bind_param(
                "ssssssssss",
                $newNoSo,
                $orderayam,
                $cKodeMember,
                $cnama,
                $expired_at,
                $totalmidtrans,
                $cnoid,
                $paymentUrl,
                $bayarmidtrans,
                $paymentData['cpayment']
            );
            $stmtPiutang->execute();
            $stmtPiutang->close();

            $delete = $conn->prepare("DELETE FROM tbkeranjang WHERE cKodeMember = ?");
            $delete->bind_param("s", $cKodeMember);
            $delete->execute();
            $delete->close();

            $paymentUrl = 'success';
            
            echo json_encode(['message' => $paymentUrl]); 

        } else {
            echo json_encode(['error' => 'No member data found']);
        }

        $stmtMember->close();
        break;

    default:
        echo json_encode(['error' => 'Invalid request method']);
        break;
}

$conn->close();
