<?php
include_once("../public/config.php");
include("../public/impOpreation.php");
include("../library/newUplode/uploadfunctions.php");
include("../library/http_call_new.php");
$do = $_GET['do'];
$today = date("Y-m-d H:i:s");
$date = date('Y-m-d');
$userid = $_SESSION['userid'];
$smarty->assign("customValidation", 1);
if (istokenexpired() && $_SESSION['auth_token']) {
    $result = refreshtoken();
    $authtoken = $_SESSION['auth_token'] = $result['data']['auth_token'];
    $_SESSION['auth_token_exp'] = time() + (int)$result['data']['expires_in'];
    R::exec("UPDATE `saudielectronicinvoice` SET `logintoken`= '$authtoken' WHERE id = 1 ");
}

$saudielectronicinvoice = R::load('saudielectronicinvoice',1);
$headers = array('Accept: application/json', 'Content-Type: application/json', "Authorization: Bearer $saudielectronicinvoice->tokenapi", "token: $saudielectronicinvoice->logintoken");
$urlapi = $saudielectronicinvoice->urlapi;
if (empty($do)) {


    $smarty->assign('saudielectronicinvoice', $saudielectronicinvoice);
    $smarty->display("header.html");
    $smarty->display("saudiElectronIcinvoiceView/saudielectronicinvoice.html");
    $smarty->display("footer.html");
} elseif ($do == "devices") {
    $devices = json_decode(HTTPRequester::HTTPGet($urlapi.'/api/v1/zatca/devices', [], $headers), true);
    $smarty->assign('devices', $devices['data']['devices']);
    $smarty->display("header.html");
    $smarty->display("saudiElectronIcinvoiceView/devices.html");
    $smarty->display("footer.html");   
} elseif ($do == "devicestatus") {
    $device = json_decode(HTTPRequester::HTTPGet($urlapi.'/api/v1/zatca/device-status/'.$_GET['deviceuuid'], [], $headers), true);
    $smarty->assign('device', $device);
    $smarty->display("header.html");
    $smarty->display("saudiElectronIcinvoiceView/devicestatus.html");
    $smarty->display("footer.html");   
} elseif ($do == "getallinvoices") {
    $data = [
      'device_uuid' => $saudielectronicinvoice->deviceuuid,
      'status' => isset($_POST['status']) ? trim($_POST['status']) : 'accepted',
      'limit' => isset($_POST['limit']) ? trim($_POST['limit']) : 50,
      'offset' => isset($_POST['offset']) ? trim($_POST['offset']) : 0,
    ];
    $getallinvoices = json_decode(HTTPRequester::HTTPGet($urlapi.'/api/v1/zatca/invoices', $data, $headers), true);
    $smarty->assign('getallinvoices', $getallinvoices['data']);
    $smarty->display("header.html");
    $smarty->display("saudiElectronIcinvoiceView/getallinvoices.html");
    $smarty->display("footer.html");   
} elseif ($do == "detail") {
    $invoice = json_decode(HTTPRequester::HTTPGet($urlapi.'/api/v1/zatca/invoice/'.$_GET['uuid'].'?include_xml=true', [], $headers), true);
    $smarty->assign('invoice', $invoice['data']);
    $smarty->display("header.html");
    $smarty->display("saudiElectronIcinvoiceView/invoice.html");
    $smarty->display("footer.html");           
} elseif ($do == "update") {
    try {
        $step = isset($_POST['step']) ? (int)$_POST['step'] : 0;
        $response = ["ok"=> false,"message"=>"خطأ غير معروف"];
        $updatesavesaudielectronicinvoice = R::load('saudielectronicinvoice',1);
        switch($step){
          case 1:
              if (!$saudielectronicinvoice->urlapi) {
                $headers = array('Accept: application/json', 'Content-Type: application/json', "Authorization: Bearer ".$_POST['tokenapi'], "token: ". $_POST['logintoken']);
                $urlapi = $_POST['urlapi'];
                $data = [
                    'email' => filter_input(INPUT_POST,"loginemail",FILTER_VALIDATE_EMAIL),
                    'password' => $_POST['loginpassword'],
                ];
              }else{
                $data = [
                    'email' => $updatesavesaudielectronicinvoice->loginemail,
                    'password' => $updatesavesaudielectronicinvoice->loginpassword
                ];
              }
            
            $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/auth/login', $data, $headers), true);
            if ($result['status'] == 'success') {
                $_SESSION['auth_token'] = $result['data']['auth_token'];
                $_SESSION['auth_token_exp'] = time() + (int)$result['data']['expires_in'];
                $data = [
                    'company_name' => $_POST['companyname'],
                    'company_branch_name' => $_POST['companybranchname'],
                    'email' => filter_input(INPUT_POST,"companyemail",FILTER_VALIDATE_EMAIL),
                    'device_name' => $_POST['devicename'],
                    'business_address' => $_POST['businessaddress'],
                    'business_category' => $_POST['businesscategory'],
                    'solution_provider_name' => $_POST['solutionprovidername'],
                    'solution_serial_number' => $_POST['solutionserialnumber'],
                    'solution_serial_number' => $_POST['solutionserialnumber'],
                    'vat_registration_number' => $_POST['vatregistrationnumber'],
                    'solution_version' => $_POST['solutionversion'],
                ];
                $headers[3] = "token: ". $_SESSION['auth_token'];
                $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/v1/zatca/generate-csr', $data, $headers), true);
                if($_POST['tokenapi']){
                $updatesavesaudielectronicinvoice->tokenapi = $_POST['tokenapi'];
                $updatesavesaudielectronicinvoice->urlapi = $_POST['urlapi'];
                $updatesavesaudielectronicinvoice->loginemail = $_POST['loginemail'];
                $updatesavesaudielectronicinvoice->loginpassword = $_POST['loginpassword'];
                $updatesavesaudielectronicinvoice->logintoken = $_SESSION['auth_token'];
                }
                $updatesavesaudielectronicinvoice->endsetup = 0;
                $updatesavesaudielectronicinvoice->licensetype = $_POST['licensetype'];
                $updatesavesaudielectronicinvoice->licensenumber = $_POST['licensenumber'];
                $updatesavesaudielectronicinvoice->streetname = $_POST['streetname'];
                $updatesavesaudielectronicinvoice->buildingnumber = $_POST['buildingnumber'];
                $updatesavesaudielectronicinvoice->neighborhood = $_POST['neighborhood'];
                $updatesavesaudielectronicinvoice->city = $_POST['city'];
                $updatesavesaudielectronicinvoice->postalzone = $_POST['postalzone'];
                $updatesavesaudielectronicinvoice->countrycode = $_POST['countrycode'];
                $updatesavesaudielectronicinvoice->companytaxregistrationnumber = $_POST['companytaxregistrationnumber'];
                $updatesavesaudielectronicinvoice->companyname = $_POST['companyname'];
                $updatesavesaudielectronicinvoice->companybranchname = $_POST['companybranchname'];
                $updatesavesaudielectronicinvoice->companyemail = filter_input(INPUT_POST,"companyemail",FILTER_VALIDATE_EMAIL);
                $updatesavesaudielectronicinvoice->devicename = $_POST['devicename'];
                $updatesavesaudielectronicinvoice->businessaddress = $_POST['businessaddress'];
                $updatesavesaudielectronicinvoice->businesscategory = $_POST['businesscategory'];
                $updatesavesaudielectronicinvoice->solutionprovidername = $_POST['solutionprovidername'];
                $updatesavesaudielectronicinvoice->solutionserialnumber = $_POST['solutionserialnumber'];
                $updatesavesaudielectronicinvoice->vatregistrationnumber = $_POST['vatregistrationnumber'];
                $updatesavesaudielectronicinvoice->solutionversion = $_POST['solutionversion'];
                $updatesavesaudielectronicinvoice->deviceuuid = $result['data']['device_uuid'];
                $updatesavesaudielectronicinvoice->deviceid = $result['data']['device_id'];
                $updatesavesaudielectronicinvoice->previousinvoicehash = 'NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==';
                $updatesavesaudielectronicinvoice->responsestepone = json_encode($result);  
                $updatesavesaudielectronicinvoice->todaynow = date("Y-m-d H:i:s");
                $updatesavesaudielectronicinvoice->useridnow = $_SESSION['userid'];
                if ($result['status'] == 'success') {
                    $updatesavesaudielectronicinvoice->stepnow = 1;
                    $response=["ok"=>true,"message"=>"تم حفظ الخطوة الأولى","errors"=>$result['errors'],'waitstep' => 1];
                } else {
                    $response=["ok"=>false,"message"=> $result['message'],"errors"=>$result['errors'],'waitstep' => 1];
                }
                R::store($updatesavesaudielectronicinvoice);
            }else {
                $response=["ok"=>false,"message"=>$result['message'],"errors"=>$result['errors'],'waitstep' => 1];
            }
            break;
          case 2:
            $data = [
                'device_uuid' => $saudielectronicinvoice->deviceuuid,
                'otp' => $_POST['otp'],
            ];
            $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/v1/zatca/validate-otp', $data, $headers), true);
                $updatesavesaudielectronicinvoice->otp = (int)$_POST['otp'];
                $updatesavesaudielectronicinvoice->responsesteptwo = json_encode($result); 
                $updatesavesaudielectronicinvoice->todaynow = date("Y-m-d H:i:s");
                $updatesavesaudielectronicinvoice->useridnow = $_SESSION['userid'];
            if ($result['status'] == 'success') {
                $updatesavesaudielectronicinvoice->stepnow = 2;
                $response=["ok"=>true,"message"=>"تم حفظ الخطوة التانية","errors"=>$result['errors'],'waitstep' => 1];
            } else {
                $response=["ok"=>false,"message"=>$result['message'],"errors"=>$result['errors'],'waitstep' => 1];
            }
            R::store($updatesavesaudielectronicinvoice);
            break;
          case 3:
            $data = [
                'device_uuid' => $saudielectronicinvoice->deviceuuid,
            ];
            $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/v1/zatca/send-compliance-invoice', $data, $headers), true);
            $updatesavesaudielectronicinvoice->responsestepthree = json_encode($result); 
            $updatesavesaudielectronicinvoice->todaynow = date("Y-m-d H:i:s");
            $updatesavesaudielectronicinvoice->useridnow = $_SESSION['userid'];
            if ($result['status'] == 'success') {
                if($result['data']['total_sent'] == 6){
                   $updatesavesaudielectronicinvoice->stepnow = 3;
                   $waitstep = 1; 
                }else{
                    $waitstep = 0; 
                }
                $response=["ok"=>true,"message"=>$result['message'],"errors"=>$result['errors'],'waitstep' => $waitstep];
            } else {
                $response=["ok"=>false,"message"=>$result['message'],"errors"=>$result['errors'],'waitstep' => 1];
            }
            R::store($updatesavesaudielectronicinvoice);
            break;  
          case 4:
            $data = [
                'device_uuid' => $saudielectronicinvoice->deviceuuid,
            ];
            $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/v1/zatca/initialize-production', $data, $headers), true);
            $updatesavesaudielectronicinvoice->responsestepfour = json_encode($result);  
            $updatesavesaudielectronicinvoice->todaynow = date("Y-m-d H:i:s");
            $updatesavesaudielectronicinvoice->useridnow = $_SESSION['userid'];
            if ($result['status'] == 'success') {
                $updatesavesaudielectronicinvoice->stepnow = 4;
                $updatesavesaudielectronicinvoice->endsetup = 1;
                $response=["ok"=>true,"message"=>"تم حفظ جميع البيانات بنجاح!","errors"=>$result['errors'],'waitstep' => 1];
            } else {
                $response=["ok"=>false,"message"=>$result['message'],"errors"=>$result['errors'],'waitstep' => 1];
            }
            R::store($updatesavesaudielectronicinvoice);
            break;
        }
        echo json_encode($response);
    } catch (Exception $e) {
        $data = array('status' => 2, 'message' => $e->getMessage());
        echo json_encode($data);
    }
} elseif ($do == "etsellbill") {


    $sellbillid = $_POST['sellbillid'];
    if (!$sellbillid) {
        exit();
    }

    $sellbill = R::getRow("SELECT * FROM `sellbill`where sellbillid =?", [$sellbillid]);
    $sellbilldetails = R::getAll("SELECT * FROM `sellbilldetail`where sellbillid =?", [$sellbillid]);
    $eclientsetting = R::findOne('esaudiclientsetting', 'clientid = ?', [$sellbill['sellbillclientid']]);
    if($sellbill['isBankAccountTransfer'] > 0){
           $payment_method = 42;
    }else if($sellbill['sellbilltotalPayed'] == 0 && $sellbill['visaPayed'] == 0){
           $payment_method = 30;
    }else if($sellbill['visaPayed'] > 0 && $sellbill['sellbilltotalPayed'] > 0){
          $payment_method = 1;
    }else if($sellbill['visaPayed'] > 0){
        $payment_method = 48;
    }else{
        $payment_method = 10;
    }

    $invoiceLines = array();
    foreach ($sellbilldetails as $sellbilldetail) {
        $product = R::getRow("SELECT * FROM `product` where productId =? ", [$sellbilldetail['sellbilldetailproductid']]);
        $array = array(
            "id" => $sellbilldetail['sellbilldetailproductid'], // max 6 chars
            "name" =>  $product['productName'],
            "unit_price" => (float) $sellbilldetail['sellbilldetailprice'],
            "quantity" =>$sellbilldetail['sellbilldetailquantity'],
            "tax_percentage" => 15.0,
            "tax_code" => "S"
        );
        array_push($invoiceLines, $array);
    }



    if($sellbill['sellbillclientid'] > 1){
        $customer_data =  [
            "license_type" => $eclientsetting->licensetype,
            "license_number" => $eclientsetting->licensenumber,
            "street_name" => $eclientsetting->streetname,
            "building_number" => $eclientsetting->buildingnumber,
            "neighborhood" => $eclientsetting->neighborhood,
            "city" => $eclientsetting->city,
            "postal_zone" => $eclientsetting->postalzone,
            "country_code" => $eclientsetting->countrycode,
            "company_name" => $eclientsetting->companyname,
        ];
    }else{
        $customer_data =  [];
    }
    
    $data = [
        "device_uuid" => $saudielectronicinvoice->deviceuuid,
        "invoice_type_code" => "0200000",
        "invoice_subtype_code" => "388",
        "invoice_number" => "INV-" . $sellbill['sellbillid'],
        "invoice_uuid" => makeUuidFromHex($sellbill['sellbillserial']),
        "invoice_counter" => $saudielectronicinvoice->invoicecounter,
        "previous_invoice_hash" => $saudielectronicinvoice->previousinvoicehash,
        "issue_date" => date("Y-m-d", strtotime($sellbill['sellbilldate'])),
        "issue_time" => date("H:i:s", strtotime($sellbill['sellbilldate'])),
        "seller_data" => [
            "license_type" =>  $saudielectronicinvoice->licensetype,
            "license_number" => $saudielectronicinvoice->licensenumber,
            "street_name" =>$saudielectronicinvoice->streetname,
            "building_number" => $saudielectronicinvoice->buildingnumber,
            "neighborhood" => $saudielectronicinvoice->neighborhood,
            "city" =>$saudielectronicinvoice->city,
            "postal_zone" => $saudielectronicinvoice->postalzone,
            "country_code" => $saudielectronicinvoice->countrycode,
            "company_tax_registration_number" => $saudielectronicinvoice->companytaxregistrationnumber,
            "company_name" => $saudielectronicinvoice->companyname
        ],
        "customer_data" =>$customer_data,
        "payment_method" => $payment_method,
        "payment_reason" => "",
        "products" => $invoiceLines
        //"discount_on_totals" => 0,
        //"charge_on_totals" => 0
    ];
    $result = json_decode(HTTPRequester::HTTPPost($urlapi.'/api/v1/zatca/submit-invoice', $data, $headers), true);
    if ($result['status_code'] >= 200 && $result['status_code'] < 300) {
        if ($result['status'] == 'success') {
            $uuid = $result['data']['invoice_uuid'];
            $qrerpids = $result['data']['qr_code'];
            R::exec("UPDATE `sellbill` SET `ereason`= 'تم قبول الفاتوره', `estatus`= '$uuid', `qrerpids`= '$qrerpids' WHERE sellbillid = $sellbillid ");
            $saudielectronicinvoice->invoicecounter = $saudielectronicinvoice->invoicecounter + 1;
            $saudielectronicinvoice->previousinvoicehash =$result['data']['invoice_hash'];
            $saudielectronicinvoice->responsebill = json_encode($result);  
            $saudielectronicinvoice->todaynow = date("Y-m-d H:i:s");
            $saudielectronicinvoice->useridnow = $_SESSION['userid'];
            R::store($saudielectronicinvoice);


            $etasellbillstatus = R::dispense('etasellbillstatus');
            $etasellbillstatus->today = date("Y-m-d H:i:s");
            $etasellbillstatus->estatus = $uuid;
            $etasellbillstatus->sellbillid = $sellbillid;
            $etasellbillstatus->submissionid = $result['data']['invoice_hash'];
            $etasellbillstatus->accepteddocuments = json_encode($result);
            $etasellbillstatus->rejecteddocuments = '';
            $etasellbillstatus->errors = '';
            R::store($etasellbillstatus);
            echo '1';
        } else {
            R::exec("UPDATE `sellbill` SET `ereason`= 'تم رفض الفاتوره', `estatus`= -1 WHERE sellbillid = $sellbillid ");
            $etasellbillstatus = R::dispense('etasellbillstatus');
            $etasellbillstatus->today = date("Y-m-d H:i:s");
            $etasellbillstatus->estatus = -1;
            $etasellbillstatus->sellbillid = $sellbillid;
            $etasellbillstatus->submissionid = '';
            $etasellbillstatus->accepteddocuments = '';
            $etasellbillstatus->rejecteddocuments = json_encode($result);
            $etasellbillstatus->rejectedmassage = $result['message'];
            $etasellbillstatus->errors = json_encode($result['errors']);
            R::store($etasellbillstatus);
            echo '2';
        }
     } else {
        R::exec("UPDATE `sellbill` SET `ereason`='حدثا خطأ اثناء الارسال', `estatus`= -2 WHERE sellbillid = $sellbillid ");
        $etasellbillstatus = R::dispense('etasellbillstatus');
        $etasellbillstatus->today = date("Y-m-d H:i:s");
        $etasellbillstatus->estatus = -2;
        $etasellbillstatus->sellbillid = $sellbillid;
        $etasellbillstatus->submissionid = 0;
        $etasellbillstatus->rejecteddocuments = json_encode($result);
        $etasellbillstatus->rejectedmassage = $result['message'];
        $etasellbillstatus->errors = json_encode($result['errors']);
        R::store($etasellbillstatus);
        echo '3';
    }    


} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}


function istokenexpired() {
    if (empty($_SESSION['auth_token']) || empty($_SESSION['auth_token_exp'])) return true;
    return (time() >= $_SESSION['auth_token_exp']);
}

function refreshtoken() {
    $saudielectronicinvoice = R::load('saudielectronicinvoice',1);
    $headers = array('Accept: application/json', 'Content-Type: application/json', "Authorization: Bearer $saudielectronicinvoice->tokenapi", "token: $saudielectronicinvoice->logintoken");
    return json_decode(HTTPRequester::HTTPPost($urlapi.'/api/auth/refresh', [], $headers), true);
}

function makeUuidFromHex($hex) {
    // لو string مش hex حوله
    if (!ctype_xdigit($hex)) {
        $hex = bin2hex($hex);
    }

    // خلي طول الـ hex 32 خانة (128bit)
    $hex = str_pad($hex, 32, "0");

    // قصّمها لشكل UUID
    return substr($hex, 0, 8) . "-" .
           substr($hex, 8, 4) . "-" .
           substr($hex, 12, 4) . "-" .
           substr($hex, 16, 4) . "-" .
           substr($hex, 20, 12);
}
// if (istokenexpired()) {
//     // نادى endpoint للتحديث (مثلاً /api/refresh) أو أعد تسجيل الدخول تلقائياً
//     $new = refreshtoken(); // دالة ترجع token جديد وتحدّث الـ session
// }

