<?php //error_reporting(E_ALL);
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/helpers.php';
require_once __DIR__.'/config.php';

use HMRC\Oauth2\AccessToken;

refreshAccessTokenIfNeeded();
$accessToken = AccessToken::get();


$taxdata=explode("|",getCompanyDetails('taxYear'));
$vatdata=explode("|",getCompanyDetails('vatData'));

$dateObj = DateTime::createFromFormat('!m', $vatdata[0]);
$monthName = $dateObj->format('F');
//echo "First month=".$monthName."<br>";

$stmt1 = $GLOBALS['con']->prepare("SELECT `totals`,`type` FROM `expenses` WHERE `date`>='".$taxdata[0]."' AND `date`<='".$taxdata[1]."'")or die(mysqli_error($GLOBALS['con']));
$stmt1->execute();$e=$stmt1->get_result();$stmt1->close();
$expcount=mysqli_num_rows($e);
while($exp=mysqli_fetch_array($e)){$expenses[]=$exp;}

$stmt2 = $GLOBALS['con']->prepare("SELECT `totals`,`items` FROM `invoices` WHERE `date_paid`>='".$taxdata[0]."' AND `date_paid`<='".$taxdata[1]."'")or die(mysqli_error($GLOBALS['con']));
$stmt2->execute();$i=$stmt2->get_result();$stmt2->close();
$invcount=mysqli_num_rows($i);
while($inv=mysqli_fetch_array($i)){$invoices[]=$inv;}

//echo "total invoices=".$invcount."<br>";
//echo "total expenses=".$expcount."<br>";

function genVat($s,$in,$out){
$stmt1 = $GLOBALS['con']->prepare("SELECT `totals` FROM `".$s."` WHERE `date`>='".$in."' AND `date`<='".$out."'")or die(mysqli_error($GLOBALS['con']));
$stmt1->execute();$e=$stmt1->get_result();$stmt1->close();
$expcount=mysqli_num_rows($e);
while($data=mysqli_fetch_array($e)){
$t=explode("|",$data['totals']);
$vat+=$t[1];
}
return $vat;
}

function genNet($s,$in,$out){
$stmt1 = $GLOBALS['con']->prepare("SELECT `totals` FROM `".$s."` WHERE `date`>='".$in."' AND `date`<='".$out."'")or die(mysqli_error($GLOBALS['con']));
$stmt1->execute();$e=$stmt1->get_result();$stmt1->close();
$expcount=mysqli_num_rows($e);
while($data=mysqli_fetch_array($e)){
$t=explode("|",$data['totals']);
$net+=$t[0];
}
return $net;

}

$submitVatReturnVatDueSales=number_format(genVat('invoices',$taxdata[0],$taxdata[1]),0);
$submitVatReturnVatDueAcquisitions=number_format("0",0);
$submitVatReturnTotalVatDue=number_format((genVat('invoices',$taxdata[0],$taxdata[1])-$submitVatReturnVatDueAcquisitions),0);
$submitVatReturnVatReclaimedCurrPeriod=number_format(genVat('expenses',$taxdata[0],$taxdata[1]),0);
$submitVatReturnNetVatDue=number_format((genVat('invoices',$taxdata[0],$taxdata[1])-genVat('expenses',$taxdata[0],$taxdata[1])));

$submitVatReturnTotalValueSalesExVAT=number_format(genNet('invoices',$taxdata[0],$taxdata[1]),0);
$submitVatReturnTotalValuePurchasesExVAT=number_format(genNet('expenses',$taxdata[0],$taxdata[1]),0);
$submitVatReturnTotalValueGoodsSuppliedExVAT=number_format("0",0);
$submitVatReturnTotalAcquisitionsExVAT=number_format("0",0);

?>
<div style="display:none">
    <div class="row">
        <div class="col-sm">
            <input type="text" class="form-control" name="client_id" placeholder="Client ID"
                   value="<?php echo $vatdata[4]; ?>">
        </div>
        <div class="col-sm">
            <input type="text" class="form-control" name="client_secret" placeholder="Client Secret"
                   value="<?php echo $vatdata[5]; ?>">
        </div>
        <div class="col-sm">
            <input type="text" class="form-control" name="server_token" placeholder="Server Token"
                   value="<?php echo $vatdata[3]; ?>">
        </div>
       
    </div>
</div>

<div style="margin-top: 10px">
    <input type="hidden" name="access_token" value="<?php echo AccessToken::get(); ?>">
    <div id="access-token-container"></div>
    <a href="javascript:void(0)" onclick="authorize()"
       class="btn btn-sm btn-warning" style="margin-top: 10px" id="create-access-token-btn">Create access token</a>
    <a href="oauth2/destroy-session.php" class="btn btn-sm btn-danger" style="margin-top: 10px"
       id="destroy-session-btn">Destroy session</a>
</div>
<div class="col-md-12" style="display:none">
<input type="text" class="form-control" name="vrn" value="<?php echo $vatdata[2]?>" placeholder="VRN">
<input type="text" class="form-control" name="vat_obligations_from" value="<?php echo date('d-m-Y',$taxdata[0])?>" placeholder="From">
<input type="text" class="form-control" name="vat_obligations_to" value="<?php echo date('d-m-Y',$taxdata[1])?>" placeholder="To">
</div>
<div class="col-md-12">
<p>Submit VAT return for period</p>
<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Period Key</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_period_key" value="<?php echo $currentVatReturnPeriodKey?>" placeholder="Period Key">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">VAT Due Sales</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_vat_due_sale" placeholder="VAT Due Sales" value="<?php echo $submitVatReturnVatDueSales; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">VAT Due Acquisitions EC</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_vat_due_acquisitions" placeholder="VAT Due Acquisitions" value="<?php echo $submitVatReturnVatDueAcquisitions; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Total VAT Due</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_total_vat_due" placeholder="Total VAT Due" value="<?php echo $submitVatReturnTotalVatDue; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">VAT Reclaimed CURR Period</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_vat_reclaimed_curr_period" placeholder="VAT Reclaimed CURR Period" value="<?php echo $submitVatReturnVatReclaimedCurrPeriod; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">NET VAT Due</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_net_vat_due" placeholder="NET VAT Due" value="<?php echo $submitVatReturnNetVatDue; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Total Value Sales EX VAT</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_total_value_sales_ex_vat" placeholder="Total Value Sales EX VAT" value="<?php echo $submitVatReturnTotalValueSalesExVAT; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Total Value Purchases EX VAT</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_total_value_purchases_ex_vat" placeholder="Total Value Purchases EX VAT" value="<?php echo $submitVatReturnTotalValuePurchasesExVAT; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Total Value Goods Supplied EC EX VAT</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_total_value_goods_supplied_ex_vat" placeholder="Total Value Goods Supplied EX VAT" value="<?php echo $submitVatReturnTotalValueGoodsSuppliedExVAT; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Total Acquisitions EC EX VAT</label>
</div>
<div class="col-sm-3">
<input type="text" class="form-control" name="submit_vat_return_total_acquisitions_ex_vat" placeholder="Total Acquisitions EX VAT" value="<?php echo $submitVatReturnTotalAcquisitionsExVAT; ?>">
</div>
</div>

<div class="form-group row">
<div class="col-sm-2">
<label for="return_period_key">Finalised Accounts?</label>
</div>
<div class="col-sm-3">
<select name="submit_vat_return_finalised" class="form-control">
<option value="0">No</option>
<option value="1" selected>Yes</option>
</select>
</div>
</div>
<div class="col-md-12 text-center">
<a href="javascript:void(0)" onclick="submitVATReturn()"><button class="btn btn-info">Submit VAT Return</button></a>
</div>
</div>
<div class="clearfix"></div>
<script>
    $(function () {
        const accessToken = $("input[name='access_token']").val();
        const features = $("#features");
        let accessTokenContainer = $("#access-token-container");
        let createAccessTokenBtn = $("#create-access-token-btn");
        let destroySessionBtn = $("#destroy-session-btn");

        if (accessToken === "") { // Doesn't have access token
            accessTokenContainer.text("Access Token: Doesn't exists.");
            destroySessionBtn.hide();
            features.hide();
        } else {
            createAccessTokenBtn.hide();
            accessTokenContainer.text("Access Token: " + accessToken);
        }
    });

    function authorize() {
        const clientId = $("input[name='client_id']").val();
        const clientSecret = $("input[name='client_secret']").val();

        let query = [];
        if (clientId !== "") query.push(`client_id=${clientId}`);
        if (clientSecret !== "") query.push(`client_secret=${clientSecret}`);
        const queryString = query.join('&');
        if (query.length) {
            location.href = 'hmrc/oauth2/create-access-token.php' + '?' + queryString;
        } else {
            location.href = 'hmrc/oauth2/create-access-token.php';
        }
    }



    function retrieveVATObligations() {
        const vrn = $("input[name='vrn']").val();
        const from = $("input[name='vat_obligations_from']").val();
        const to = $("input[name='vat_obligations_to']").val();
        const status = $("input[name='vat_obligations_status']").val();
        const govTestScenario = $("input[name='vat_obligations_gov_test_scenario']").val();

        let query = [];

        if (vrn !== "") query.push(`vrn=${vrn}`);
        if (from !== "") query.push(`from=${from}`);
        if (to !== "") query.push(`to=${to}`);
        if (status !== "") query.push(`status=${status}`);
        if (govTestScenario !== "") query.push(`gov_test_scenario=${govTestScenario}`);
        const queryString = query.join('&');
        if (query.length) {
            $.post("hmrc/vat/get-vat-obligations.php?"+queryString,function(ret){$('#viewVatObs').html(ret);})
            
        } else {
            location.href = "hmrc/vat/get-vat-obligations.php";
        }
    }

    function submitVATReturn() {alert()
        const vrn = $("input[name='vrn']").val();
        const periodKey = $("input[name='submit_vat_return_period_key']").val();
        const vatDueSale = $("input[name='submit_vat_return_vat_due_sale']").val();
        const vatDueAcquisitions = $("input[name='submit_vat_return_vat_due_acquisitions']").val();
        const totalVatDue = $("input[name='submit_vat_return_total_vat_due']").val();
        const vatReclaimedCurrPeriod = $("input[name='submit_vat_return_vat_reclaimed_curr_period']").val();
        const NetVatDue = $("input[name='submit_vat_return_net_vat_due']").val();
        const totalValueSalesEXVat = $("input[name='submit_vat_return_total_value_sales_ex_vat']").val();
        const totalValuePurchasesEXVat = $("input[name='submit_vat_return_total_value_purchases_ex_vat']").val();
        const totalValueGoodsSuppliedEXVat = $("input[name='submit_vat_return_total_value_goods_supplied_ex_vat']").val();
        const totalAcquisitionsEXVat = $("input[name='submit_vat_return_total_acquisitions_ex_vat']").val();
        const finalised = $("select[name='submit_vat_return_finalised']").val();
        const govTestScenario = $("input[name='submit_vat_return_gov_test_scenario']").val();

        let query = [];
        if (vrn !== "") query.push(`vrn=${vrn}`);
        if (periodKey !== "") query.push(`period_key=${periodKey}`);
        if (vatDueSale !== "") query.push(`vat_due_sale=${vatDueSale}`);
        if (vatDueAcquisitions !== "") query.push(`vat_due_acquisitions=${vatDueAcquisitions}`);
        if (totalVatDue !== "") query.push(`total_vat_due=${totalVatDue}`);
        if (vatReclaimedCurrPeriod !== "") query.push(`vat_reclaimed_curr_period=${vatReclaimedCurrPeriod}`);
        if (NetVatDue !== "") query.push(`net_vat_due=${NetVatDue}`);
        if (totalValueSalesEXVat !== "") query.push(`total_value_sales_ex_vat=${totalValueSalesEXVat}`);
        if (totalValuePurchasesEXVat !== "") query.push(`total_value_purchases_ex_vat=${totalValuePurchasesEXVat}`);
        if (totalValueGoodsSuppliedEXVat !== "") query.push(`total_value_goods_supplied_ex_vat=${totalValueGoodsSuppliedEXVat}`);
        if (totalAcquisitionsEXVat !== "") query.push(`total_acquisitions_ex_vat=${totalAcquisitionsEXVat}`);
        if (finalised !== "") query.push(`finalised=${finalised}`);
        if (govTestScenario !== "") query.push(`gov_test_scenario=${govTestScenario}`);
        const queryString = query.join('&');
        if (query.length) {
           $.post("hmrc/vat/submit-vat-return.php?"+queryString,function(ret){alert(ret)})
        } else {
            location.href = "hmrc/vat/submit-vat-return.php";
        }
    }

    function viewVATReturn() {
        const vrn = $("input[name='vrn']").val();
        const periodKey = $("input[name='view_vat_return_period_key']").val();
        const govTestScenario = $("input[name='view_vat_return_gov_test_scenario']").val();

        let query = [];
        if (vrn !== "") query.push(`vrn=${vrn}`);
        if (periodKey !== "") query.push(`period_key=${periodKey}`);
        if (govTestScenario !== "") query.push(`gov_test_scenario=${govTestScenario}`);
        const queryString = query.join('&');
        if (query.length) {
            
             $.post("hmrc/vat/view-vat-return.php?"+queryString,function(ret){$('#viewVatReturn').html(ret);})
        } else {
            location.href = "hmrc/vat/view-vat-return.php";
        }
    }
</script>

<script>
$('#navBox').html('<a href="index.php?t=includes/finance&p=finance_invoices.php" class="s1">Finance</a><a href="javascript:void(0)" class="sa">Vat Submission</a>');
</script>
