<?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 = isset($memberData['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 
                    ? AS cNoSo, t.cNoID, t.cKodeBrg, t.cNamaBrg AS cNama, t.nQty AS nQty1, 1 AS nIsi, t.cSat AS cSat, 
                    0 AS nQty2, 0 AS lnStock, '' AS cSat2, 0 AS nTotQty, '' AS cSat3, 0 AS nIsi2, 0 AS nQty3, 
                    0 AS nIsi3, 0 AS nQty4, '' AS cSat4, '' AS cSat5, 0 AS nIsi4, '' AS cHal, t.ID AS cNoDtl, 
                    '', 'Spesifikasi' AS cspesifikasi, t.nHarga AS nharga, t.nSTotal AS nStotal, 
                    t.nDisc1 AS nDisc, t.nDisc2 AS nDisc2, t.nDisc3 AS nDisc3, t.nDisc4 AS nDisc4 , 0 AS nCol, 0 AS nDiscPersen 
                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);
                if ($stmtInsert) {
                    $stmtInsert->bind_param("ss", $newNoSo, $cKodeMember);
                    
                    if ($stmtInsert->execute()) {
                        
                        $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();
                        $courierResult = $stmtCourier->get_result();
                        
                        if ($courierResult->num_rows > 0) {
                            $courierData = $courierResult->fetch_assoc();
                        
                            $cjnskurir = $courierData['cjnskurir'];
                            $cnamakurir = $courierData['cnamakurir'];
                            $ckodekurir = $courierData['ckodekurir'];
                            $cservicekurir = $courierData['cservicekurir'];
                            $cdescriptionkurir = $courierData['cdescriptionkurir'];
                            $ccostkurir = $courierData['ccostkurir'];
                            
                            $cleanedCost = str_replace(['Rp', '.', ' '], '', $ccostkurir);

                            $cleanedCost = (float)$cleanedCost;
                            $cetdkurir = $courierData['cetdkurir'];
                        } else {
                            echo json_encode(['error' => 'Courier data not found']);
                            exit();
                        }

                        $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,$cjnskurir, $cnamakurir, $ckodekurir, $cservicekurir, $cdescriptionkurir, $ccostkurir, $cetdkurir, $cleanedCost);
                        $stmtSO->execute();
                        $stmtSO->close();
                        
                        $queryStockApp = "
                            INSERT INTO tbstockaplikasi (
                                cnomer, dtanggal, ckode, cnama, ckodebrg, cnamabrg, cnoid, cpos, nqty, csat, nisi, ntotqty, ntotqtyreal, nhrgjual, ntotal, cid
                            )
                            SELECT
                                ? AS cnomer, CURDATE() AS dtanggal, ?, ?, t.cKodeBrg, b.cNama, t.cNoID, '' AS cPos, -t.nQty, t.cSat, 1 AS nIsi, 
                                -t.nQty AS nTotQty, -t.nQty AS nTotQtyReal, t.nHarga AS nHargaJual, t.nSTotal AS nTotal, '' AS cid
                            FROM tbkeranjang t
                            JOIN tbbarang b ON t.cKodeBrg = b.cKode
                            WHERE t.cKodeMember = ?
                        ";
                        
                        $stmtStockApp = $conn->prepare($queryStockApp);
                        if ($stmtStockApp === false) {
                            echo json_encode(['error' => 'Failed to prepare query: ' . $conn->error]);
                            exit();
                        }
                        
                        $stmtStockApp->bind_param("ssss", $newNoSo, $cKodeMember, $cnama,  $cKodeMember);
                        
                        if ($stmtStockApp->execute()) {
                            
                            $queryPayment = "SELECT ckode AS ckodepayment, cpayment AS cnamapayment, clink AS clinkpayment, cwaktu FROM tbjnspayment WHERE ckode = ?";
                            $stmtPayment = $conn->prepare($queryPayment);
                            $stmtPayment->bind_param("s", $bayarmidtrans);
                            $stmtPayment->execute();
                            $paymentResult = $stmtPayment->get_result();
                        
                            if ($paymentResult->num_rows > 0) {
                                $paymentData = $paymentResult->fetch_assoc();
                                $ckodepayment = $paymentData['ckodepayment'];
                                $cnamapayment = $paymentData['cnamapayment'];
                                $clinkpayment = $paymentData['clinkpayment'];
                                $cwaktu = $paymentData['cwaktu'];
                                $datetime_jakarta = new DateTime();
                                $datetime_jakarta->modify("+$cwaktu minutes");

                                $expired_at = $datetime_jakarta->format('Y-m-d H:i:s');
                                
                            } else {
                                echo json_encode(['error' => 'Payment method not found']);
                                exit();
                            }
                            $stmtPayment->close();
                            
                            $orderayam = $newNoSo . time();
                            
                            // asli
                            // $serverKey = "Mid-server-2rLeciA_Akid6kdVb7el3Fvs";
                            
                            // sandbox
                            $serverKey = "Mid-server-AGyISGYL0OVVyNhML0c-vQ55"; //karya bintang
                            $transactionDetails = [
                                'order_id' => $orderayam, 
                                'gross_amount' => $totalmidtrans, 
                            ];

    
                            $customerDetails = [
                                'first_name' => $cnama,
                                'last_name' => '',
                                'email' => $cemail,
                                'phone' => $cnohp,
                            ];
    
                            $paymentType = $clinkpayment; 
                            
                            $requestBody = [
                                'transaction_details' => $transactionDetails,
                                'customer_details' => $customerDetails,
                            ];
                            
                            // asli
                            // $ch = curl_init("https://api.midtrans.com/snap/v1/transactions");
                            
                            // sandbox
                            $ch = curl_init("https://api.sandbox.midtrans.com/snap/v1/transactions");
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                                'Authorization: Basic ' . base64_encode($serverKey . ':'),
                                'Content-Type: application/json',
                            ]);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestBody));
                            
                            $response = curl_exec($ch);
                            curl_close($ch);
                            
                            if ($response === false) {
                                echo json_encode(["error" => "Failed to generate token from Midtrans"]);
                                exit;
                            }
                            
                            $responseData = json_decode($response, true);
                            if (isset($responseData['status_code']) && $responseData['status_code'] != '200') {
                                echo "Error: " . (isset($responseData['status_message']) ? $responseData['status_message'] : 'Unknown error');
                                exit;
                            }
                            
                            if (isset($responseData['token']) && isset($responseData['redirect_url'])) {
                                $token = $responseData['token'];
                                $paymentUrl = $responseData['redirect_url'] . "#/" . $paymentType; 
                                
                                $id = 'A';
                            
                                $insertPiutangQuery = "
                                    INSERT INTO tbpiutang (
                                        cnomer, dtanggal, cid, cnoorder, ckdcust, cnmcust, dtglorder, etglexpired, 
                                        nnominal, cnoid, clinkpembayaran, cstatuspembayaran, cjnsbiaya, cnamabiaya
                                    )
                                    VALUES (?, CURDATE(), ?, ?, ?, ?, CURDATE(), ?, ?, ?, ?, 'pending' , ?, ?)
                                ";
                                
                                $insertPiutangStmt = $conn->prepare($insertPiutangQuery);
                                
                                if ($insertPiutangStmt) {
                                    $insertPiutangStmt->bind_param("sssssssssss", $newNoSo, $id, $orderayam,  $cKodeMember,$cnama,   $expired_at, $totalmidtrans,  $cnoid,  $paymentUrl, $bayarmidtrans, $cnamapayment);
                                    
                                    if ($insertPiutangStmt->execute()) {
                                        $deleteQuery = "DELETE FROM tbkeranjang WHERE cKodeMember = ?";
                                        $deleteStmt = $conn->prepare($deleteQuery);
                                        if ($deleteStmt) {
                                            $deleteStmt->bind_param("s", $cKodeMember);
                                            $deleteStmt->execute();
                                            $deleteStmt->close(); 
                                            
                                            echo json_encode(['message' => $paymentUrl]);
                                        } else {
                                            echo json_encode(['error' => 'Failed to delete from tbkeranjang']);
                                        }
                                    } else {
                                        echo json_encode(['error' => 'Failed to insert into tbpiutang']);
                                    }
                        
                                    $insertPiutangStmt->close();
                                }
                            } else {
                                echo "Error: Unexpected response from Midtrans.";
                            }
                        } else {
                            echo json_encode(['error' => 'Failed to execute insert into tbstockaplikasi: ' . $stmtStockApp->error]);
                        }
                        
                        $stmtStockApp->close();

                    } else {
                        echo json_encode(['error' => 'Failed to execute insert query']);
                    }
                    $stmtInsert->close();
                } else {
                    echo json_encode(['error' => 'Failed to prepare insert statement']);
                }
                
            } else {
                echo json_encode(['error' => 'No member data found for the given cKodeMember']);
            }

            $stmtMember->close(); 
        break;

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

$conn->close();

?>
