<?php

require_once "../../config.php";
require_once "../../validation.php";
require_once "../../Helper.php";
require_once "../../ajax/send_email.php";
require_once "check_edit_page_ajax.php";

include_once "../../ichat/admin/route.php";
if ($session->is_logged_in() != true ) {
        redirect_to(WEB_LINK.'/login');
} else {
    $current_user = User::get_specific_id($session->admin_id);
    $current_user->set_online();
    $group = $current_user->prvlg_group;
}


require_once("../../ichat/admin/assets/includes/Library/SessManager.php");
require_once("../../ichat/admin/assets/includes/Library/User.php");
$session = new  SessManager();

require_once '../database1.php';
class convertToInvoice extends database
{
    public function index($checkoutID)
    {
        $this->dbh = $this->connectPDO1();
        $this->dbh->beginTransaction();
        try
        {
            $count = $this->current_count();
            $data['cl_invoice_no'] = $count['cl_prefix'] . '-' . $count['cl_count'];
            $data1['cl_count'] = $count['cl_count'] + 1;
            $where1['cl_id'] = $count['cl_id'];

            $autoID = $this->update1('tb_auto_incre', $data1, $where1);
            if(!$autoID)
            {
                $this->dbh->rollback();
                return 0;
                exit;
            }

            $data['cl_invoice'] = 1;
        	$where['cl_id'] = $checkoutID;
            $res = $this->update('tb_checkout',$data, $where);
            if(!$res)
            {
                $this->dbh->rollback();
                return 0;
                exit;
            }
            $this->dbh->commit();
            return $data['cl_invoice_no'];
            exit;
        }
        catch (PDOException $e) {
            // roll back transaction
            $this->dbh->rollback();
            return 0;
        }
    }

    public function getCheckout($checkoutID)
    {
        return $this->fetchRow('tb_checkout', ['cl_id' => $checkoutID]);
    }

    public function current_count()
    {
        $where['cl_type'] = 'Invoice';
         return $this->fetchRow('tb_auto_incre', $where);
    }

    public function getAllCheckoutItems($checkoutID)
    {
        $sql = " SELECT ci.*, p.cl_name FROM tb_checkout_item ci INNER JOIN tb_product p ON ci.cl_product_id=p.cl_id WHERE ci.cl_deleted_at IS NULL AND ci.cl_checkout_id=? ";
        $where[] = $checkoutID;
        return $this->callQuery($sql, $where);
    }
}

if(!isset($_GET['id']) || !is_numeric($_GET['id']))
{
    http_response_code(400);
    echo json_encode(array('error_text' => 'Order Not Found'));
    exit;
}

$checkoutID = $_GET['id'];

$obj = new convertToInvoice();
$checkout = $obj->getCheckout($checkoutID);
if(!$checkout)
{
    http_response_code(400);
    echo json_encode(array('error_text' => 'Checkout Not Found'));
    exit;
}

$checkoutItems = $obj->getAllCheckoutItems($checkoutID);

$invoiceNo = $obj->index($id);
if(!$invoiceNo)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

$body = '<table style="width:100%;border:1px solid lightgray"><tr><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px" colspan="2">Sveicināti, ' . $checkout['cl_fname'] . ' ' . $checkout['cl_surname'] . '</td></tr><tr><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px" colspan="2">Atsaucoties uz Jūsu pasūtījumu interneta veikalā www.eretail.lv, pielikumā nosūtām rēķinu par pasūtījumu.</td></tr><tr><td colspan="2" style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">Lūdzam apmaksāt rēķinu, norādot tā numuru: ' . $invoiceNo . '<br/><br/>
Rekvizīti apmaksas veikšanai:<br/>
SIA eretail<br/>
Konta nr: LV91HABA0551047394325<br/>
Banka: AS Swedbank<br/>
Reģ.nr:  51203062881<br/><br/>
Nenorādot rēķina numuru, maksājuma apstrāde var aizkavēties. Lai garantētu laicīgi preces piegādi, lūdzam, veikt pasūtījuma apmaksu pēc iespējas ātrāk*.</td></tr>';
$body.= '<tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px;width: 170px">Vārds Uzvārds</th><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $checkout['cl_fname'] . ' ' . $checkout['cl_surname'] . '</td></tr>';
$body.= '<tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px;width: 170px">Pilsēta</th><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $checkout['cl_city'] . '</td></tr>';
$body.= '<tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px;width: 170px">Adrese</th><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $checkout['cl_address'] . '</td></tr>';
$body.= '<tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px;width: 170px">Pasta indekss</th><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $checkout['cl_pasta_indeks'] . '</td></tr>';

$body.= '<tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px;width: 170px">Apmaksas veids</th><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $checkout['cl_payment_type'] . '</td></tr>';

$body.= '</table>';

$total = 0;

$body.= '<table style="width:100%;border:1px solid lightgray;margin-top:15px">';
if(!empty($checkoutItems))
{
    $body.= '<thead><tr><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">Pasūtītās preces</th><th style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">Kopējais preču daudzums</th><th style="text-align:left;border-bottom:1px solid lightgray;border-right:1px solid lightgray;;padding:15px">Cena</th></tr></thead><tbody>';
    foreach($checkoutItems AS $item)
    {
        $body.= '<tr><td style="text-align:left;border-bottom:1px solid lightgray;border-right:1px solid lightgray;;padding:15px">' . $item['cl_name'] . '</td><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $item['cl_quantity'] . '</td><td style="text-align:left;border-bottom:1px solid lightgray;;padding:15px">' . $item['cl_amount'] . '</td></tr>';
        $total+= $item['cl_amount'];
    }
}
$body.= '</tbody><tfoot>';
$body.= '<tr><td colspan="3" style="text-align:right">Cena: ' . $total . ' €</td></tr>';
$body.= '<tr><td colspan="3" style="text-align:right">Piegādes maksa: ' . $checkout['cl_pvn'] . ' €</td></tr>';
$body.= '<tr><td colspan="3" style="text-align:right">Pavisam kopā: ' . $checkout['cl_total'] . ' €</td></tr>';
$body.= '</tfoot></table>';

$emailRes = send_email($checkout['cl_email'], $checkout['cl_fname'], 'eretail.LV - Invoice # ' . $invoiceNo, $body);

session_start();
$_SESSION['error_message'] = 'Order Converted to Invoice Successfully';
$_SESSION['error_type'] = 'success';

http_response_code(200);
echo json_encode(array('message' => 'Order Converted to Invoice Successfully'));
exit;
