<?php
session_start();
header("Access-Control-Allow-Origin:*");
include 'connect.php';

if (isset($_REQUEST['bank_id'])) {


    try {
        $data = array();
        $dir = "slip/" . date('Ym');

        if (!is_dir($dir)) {
            mkdir($dir);
        }
        // $filepic = $dir . basename($_FILES['file']['name']); // ชื่อไฟล์เดิม
        $slip_name = $_REQUEST['username'] . '_' . date('YmdHis');
        $sourcePath = $_FILES['file']['tmp_name'];
        $targetPath = $dir . "/"  . $slip_name . ".jpg";
    
       // $targetPath = 'C:/AppServ/www/payment/slip/202404/' . $slip_name . '.jpg';
        $line_slip = $_SERVER['HTTP_HOST'] . '/slip/' . date('Ym') . '/' . $slip_name . '.jpg';

        copy($sourcePath, $targetPath);





        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://developer.easyslip.com/api/v1/verify',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('file' => new CURLFILE($targetPath)),
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer 2c63b085-f22e-4706-b5e8-d47b982625af'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $obj = json_decode($response, true);

        $name_receive_en = $obj['data']['receiver']['account']['name']['en'];
        $name_receive_th = $obj['data']['receiver']['account']['name']['th'];
        $bank_receive = $obj['data']['receiver']['bank']['name'];
        $amount = $obj['data']['amount']['amount'];
        $trans = $obj['data']['transRef'];
        $date = $obj['data']['date'];
        $bank_receive_number = $obj['data']['receiver']['account']['bank']['account'];
        $cusname = $obj['data']['sender']['account']['name']['th'];

        if ($trans == '') {
            $data = array("date_slip" => $date, "status" => '4', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);
            echo json_encode($data);
            $msg = $_REQUEST['username'] . "\n" . 'ตรวจสอบสลิปไม่ได้ ' . "\n" .   $line_slip;
            $token_id = 1;
            include 'line_notify.php';
            exit();
        }

        $date_slip = substr($date, 0, 10);
        $time_slip = substr($date, 11, 8);
        $limit_date = date("Y-m-d", strtotime("-2 day", strtotime(date('Y-m-d'))));

        if ($date_slip < $limit_date) {
            $data = array("date_slip" => $date, "status" => '5', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);
            echo json_encode($data);
            $msg = $_REQUEST['username'] . "\n" . 'อายุสลิปเกิน 1 วัน ' .   $line_slip;
            $token_id = 1;
            include 'line_notify.php';
            exit();
        }

        $sql = $con->prepare('select trans_id from slip_log where trans_id=?');
        $sql->execute(array($trans));
        $me = 0;
        foreach ($sql as $c) {
            $me = 1;
        }
        if ($me == 1) {
            $data = array("date_slip" => $date, "status" => '3', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);
            echo json_encode($data);
            $msg = $_REQUEST['username'] . "\n" . 'สลิปนี้ถูกใช้งานไปแล้ว ส่งสลิปซ้ำ ' .   $line_slip;
            $token_id = 1;
            include 'line_notify.php';
            exit();
        }


        $bank_number = '';

        for ($i = 0; $i < strlen($bank_receive_number); $i++) {
            if (substr($bank_receive_number, $i, 1) != 'x' && substr($bank_receive_number, $i, 1) != 'X' && substr($bank_receive_number, $i, 1) != '-') {
                $bank_number = $bank_number . substr($bank_receive_number, $i, 1);
            } else {
                $bank_number = $bank_number . '%';
            }
        }



        $sql = $con->prepare('select * from bank where id=? and bank_number like ? and bank_type like ? and bank_name like ? or 
    id=? and bank_number like ? and bank_type like ? and name_en like ?');
        $sql->execute(array(
            $_REQUEST['bank_id'], '%' . $bank_number . '%', '%' . $bank_receive . '%', '%' .  $name_receive_th . '%',
            $_REQUEST['bank_id'], '%' . $bank_number . '%', '%' . $bank_receive . '%', '%' .  $name_receive_th . '%'
        ));
        $me = 0;

        foreach ($sql as $c) {

            if ($_REQUEST['totalamountpay'] != $amount) {
                $data = array("date_slip" => $date, "status" => '2', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);
                $me = 2;
               $msg = $_REQUEST['username'] . "\n" . 'ยอดชำระไม่ถูกต้อง' . "\n" . 'ต้องชำระ ' . $_REQUEST['totalamountpay'] . "\n" .  ' ยอดที่ชำระเข้ามา  ' . $amount . "\n" .   $line_slip;
                $token_id = 1;
                include 'line_notify.php';
            } else {
                $me = 4;
                $data = array("date_slip" => $date, "status" => '4', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);

                $sql2 = $con->prepare('select * from sub where user=?');
                $sql2->execute(array($_REQUEST['username']));
                foreach ($sql2 as $c2) {


                    $next_lot = date("Y-m-d", strtotime("16 day", strtotime(date('Y-m-d'))));
                    $sql4 = $con->prepare('select * from lot where lot >= ? and lot < ? LIMIT 1');
                    $sql4->execute(array(date('Y-m-d'), $next_lot));
                    foreach ($sql4 as $c4) {
                        $lot = $c4['lot'];
                    }


                    $due_date = date("Y-m-d", strtotime("26 day", strtotime($lot)));
                    $sql4 = $con->prepare('select * from lot where lot >= ? order by lot asc LIMIT 1');
                    $sql4->execute(array($due_date));
                    foreach ($sql4 as $c4) {
                        $next_due = $c4['lot'];
                    }




                    $sql3 = $con->prepare('select * from host where id=?');
                    $sql3->execute(array($c2['host_id']));
                    foreach ($sql3 as $c3) {
                        $convs = new PDO('mysql:host=' . $c3['ipaddress'] . '; dbname=' . $c2['dbname'] . ';charset=utf8;', $c3['dbuser'], $c3['dbpass']);
                      

                        $sqlx = $con->prepare('select * from prepare_payment where priroot=? and status=? and subdomain=? and ip=?');
                        $sqlx->execute(array($_REQUEST['priroot'], 'รอชำระ',$_REQUEST['subdomain'],$c3['ipaddress']));
                        foreach ($sqlx as $cx) {
                            $timecycle = date("Y-m-d", strtotime("-1 day", strtotime($cx['next_lot'])));
                           if($_REQUEST['webtype']==0)
                            {
                                $sqlvs = $convs->prepare('update ' . $c2['tbuser'] . ' set timecycle=?,date_pay=?,type=? where id=?');
                                $sqlvs->execute(array($timecycle,$date,'user',$cx['userid']));
                            }else if($_REQUEST['webtype']==1)
                            {
                                $sqlvs = $convs->prepare('update ' . $c2['tbuser'] . ' set timecycle=?,date_pay=? where id=?');
                                $sqlvs->execute(array($timecycle,$date,$cx['userid']));

                                $sqlvs = $convs->prepare('update ' . $c2['tbuser'] . ' set timecycle=?,date_pay=?,type=? where type <> ?');
                                $sqlvs->execute(array($timecycle,$date,'agent','Main'));
                            }

                            $sqlx1 = $con->prepare('delete from next_due where txtnote=?');
                            $sqlx1->execute(array($cx['user']));

                            $sqlx1 = $con->prepare('insert into next_due(lot,user,amount,date,codeedit,priroot,due_date,webtype,host_id,txtnote) values (?,?,?,?,?,?,?,?,?,?)');
                            $sqlx1->execute(array($lot, $_REQUEST['username'], $cx['amount'], date('Y-m-d H:i:s'), $trans, $_REQUEST['priroot'], $cx['next_lot'], $c2['type'], $c2['host_id'], $cx['user']));
                       
                            $sqlx1=$con->prepare('update prepare_payment set status = ? where id=?');
                            $sqlx1->execute(array('สำเร็จ',$cx['id']));
                        }


                        $sqlx2 = $con->prepare('insert into payment(user,amount,codeedit,priroot,webtype,host_id,lot,txtnote,due_date,bank_id,link_slip) values (?,?,?,?,?,?,?,?,?,?,?)');
                        $sqlx2->execute(array($_REQUEST['username'], $amount, $trans, $_REQUEST['priroot'], $c2['type'], $c2['host_id'], $lot, 'Slip verify', $next_due, $_REQUEST['bank_id'], $line_slip));
                    
                       
                    }



                    $sql1 = $con->prepare('insert into slip_log(trans_id,user,cusname,bank_number,bank_name,bank_type,amount,date_trans) values(?,?,?,?,?,?,?,?)');
                    $sql1->execute(array($trans, $_REQUEST['username'], $cusname, $bank_receive_number, $name_receive_th, $bank_receive, $amount, $date));

                    $sql1 = $con->prepare('select SUM(amount) as amount_oflot from payment where lot=? and del=?');
                    $sql1->execute(array($lot, 0));
                    $amount_of_lot = 0;
                    foreach ($sql1 as $c1) {
                        $amount_of_lot = number_format($c1['amount_oflot']);
                    }

                    $me = 1;
                    $data = array("date_slip" => $date, "status" => '1', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount);
                    $msg = $_REQUEST['username'] . "\n" . 'ชำระค่าบริการ ' . $amount . ' บาท สำเร็จ' . "\n" . 'วันที่โอน : ' . $date_slip .  "\n" . 'เวลา ' . $time_slip . "\n" . 'รายได้ประจำงวด ' . $amount_of_lot . ' บาท' . "\n" .   $line_slip;
                    $token_id = 2;
                    include 'line_notify.php';
                }
            }
        }
        if ($me != 0) {
            echo json_encode($data);
        } else {
            $data = array("date_slip" => $date, "status" => '0', "trans" => $trans, "trans_need" => $_REQUEST['totalamountpay'], "trans_amount" => $amount, "bank_re" => $bank_receive);
            $msg = $_REQUEST['username'] . "\n" . 'โอนผิดบัญชี ' . "\n" . 'ที่ต้องโอน : '  . $_REQUEST['bank_name'] . "\n" . 'ที่โอนมา : ' . $name_receive_th  . "\n" . $line_slip;
            $token_id = 1;
            include 'line_notify.php';

            echo json_encode($data);
        }

        // echo $me;
        //echo $name_receive_en . '<br>' . $name_receive_th . '<br>' . $bank_receive . '<br>' . $amount . '<br>' . $trans . '<br>' . $date . '<br>' . $bank_receive_number;
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}
