<?php
require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';

require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketinvoiceprinting.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketnaplo.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/doc/pdf_crabe_new_printinginvoice.modules.php';
require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/doc/pdf_crabe_receipt.modules.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/bbticketcounter.class.php';




if (isModEnabled('project')) {
    require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
}

global $db, $conf;

$statuses = array("OK", "Lejárt", "Érvénytelen");

// Load translation files required by the page
$langs->loadLangs(array('bills', 'companies'));

$id = (GETPOST('id') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
$ref = GETPOST('ref', 'alpha');
$lineid = GETPOST('lineid', 'int');
$socid = GETPOST('socid', 'int');
$action = GETPOST('action', 'aZ09');
$timestamp = GETPOST('timestamp', 'alpha');

$Bbticketcounter = new Bbticketcounter();

//print_r($_REQUEST);

// Kikeresem a facture_id-hoz tartozó jegyeket a llx_bbus_bbticketinvoiceprinting táblából. Osszekotni: user, jegy adatok (bbticket), hol hasznaltak
$res = getBbticketinvoiceprinting($id);

// Security check
if ($user->socid) {
    $socid = $user->socid;
}

$object = new Facture($db);
// Load object
if ($id > 0 || !empty($ref)) {
    $ret = $object->fetch($id, $ref, '', '', (!empty($conf->global->INVOICE_USE_SITUATION) ? $conf->global->INVOICE_USE_SITUATION : 0));
}

$result = restrictedArea($user, 'facture', $object->id);


/*
 * View
 */

$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('ContactsAddresses');
$helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
llxHeader('', $title, $helpurl);

$form = new Form($db);
$formcompany = new FormCompany($db);
$contactstatic = new Contact($db);
$userstatic = new User($db);
$PDF_Crabe = new pdf_crabe_new_printinginvoice($db);
$PDF_Crabe_receipt = new pdf_crabe_receipt($db);

function getBbticketinvoiceprinting($id)
{
    global $db;
    $bbticketinvoiceprinting = new BbTicketInvoicePrinting($db);

    $sql = "SELECT product.label, ticket.available_at, ticket.validated_at, ticket.expire_at, ticket.usable_occasions, ticket.usage, tip.date_creation, tip.ticket_id, ticket.bundle_id, ticket.ticket_id as product_id, tip.printing_date, usr.lastname, usr.firstname  
    FROM " . $db->prefix() . $bbticketinvoiceprinting->table_element . " AS tip
    INNER JOIN llx_user as usr ON tip.fk_user_creat = usr.rowid
    INNER JOIN llx_bbus_bbticket as ticket ON tip.ticket_id = ticket.rowid
    INNER JOIN llx_product AS product ON ticket.ticket_id = product.rowid
    WHERE tip.fk_facture = {$id}";
    //print $sql;
    return $db->query($sql);
}

function getTicketnaploByTicketId($id)
{
    global $db;
    $bbticketNaplo = new BbTicketNaplo($db);
    $sql = "SELECT
    loc.location_name,
    loc.available_services,
    naplo.date_creation AS naplo_date_creation,
    naplo.status,
    devices.device_name,
    devices.device_function,
    devices.device_type,
    devices.ref
FROM
" . $db->prefix() . $bbticketNaplo->table_element . " as naplo
    LEFT JOIN llx_bbus_bbdevices AS devices ON naplo.device_id = devices.rowid AND naplo.device_id IS NOT NULL
    LEFT JOIN llx_bbus_bbdevicesservicelocation as ds ON ds.rowid = naplo.bbservicelocation_id
    LEFT JOIN llx_bbus_bbservicelocation AS loc ON ds.service_location_id = loc.rowid AND naplo.bbservicelocation_id IS NOT NULL
WHERE
ticket_row_id = {$id} ORDER BY naplo_date_creation DESC";
    return $db->query($sql);
}

function getQRcode($facture_id, $ticket_id)
{
    global $db;
    $sql = "SELECT bbti.printing_date_timestamp AS timestamp FROM llx_bbus_bbticketinvoiceprinting AS bbti
    INNER JOIN llx_facture as f ON f.rowid = bbti.fk_facture
    WHERE bbti.fk_facture = {$facture_id}
    AND bbti.ticket_id = {$ticket_id}";
    $result = $db->query($sql);
    if (pg_num_rows($result) > 0) {
        $data = pg_fetch_assoc($result);
        return $data['timestamp'];
    }
    return '';
}

function createPDFButton($id, $ticket_id)
{
    global $langs;
    $string = '';
    $QRCode = getQRcode($id, $ticket_id);
    if ($QRCode != '') {
        $string = '<a href="/custom/bbus/views/printview.php?id=' . $id . '&timestamp=' . $QRCode . '" name="timestamp">' . $langs->trans('GenerateInvoice') . '</a>';
    }
    return $string;
}

if ($timestamp !== '') {
    if ($object->type == 7) {
        $result = $PDF_Crabe_receipt->write_file($object, $langs, $timestamp);
    } else {
        $result = $PDF_Crabe->write_file($object, $langs, $timestamp);
    }
    if ($result == 1) {
        setEventMessage($langs->trans('InvoiceReady'));
    } else {
        setEventMessage($langs->trans('InvoiceFailed'), 'error');
    }
}

function setColor($status)
{
    return $status == 0 ? 'green' : 'red';
}

/* *************************************************************************** */
/*                                                                             */
/* View and edit mode                                                         */
/*                                                                             */
/* *************************************************************************** */

if ($id > 0 || !empty($ref)) {
    if ($object->fetch($id, $ref) > 0) {
        $object->fetch_thirdparty();

        $head = facture_prepare_head($object);

        $totalpaid = $object->getSommePaiement();

        print dol_get_fiche_head($head, 'tickets', $langs->trans('InvoiceCustomer'), -1, 'bill');
        print '<input type="hidden" id="printedTicketsNumber" name="printedticketsnumber" value="' . $Bbticketcounter->numberOfPrintedTickets . '">';

        // Invoice content

        $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';

        $morehtmlref = '<div class="refidno">';
        // Ref customer
        $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
        $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
        // Thirdparty
        $morehtmlref .= '<br>' . $langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer');

        $morehtmlref .= '</div>';

        $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status

        dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);

        $content = '';
        $content .= '<table class="centpercent noborder listaction">';
        $content .= '<tr class="liste_titre">';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('TicketId') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('TicketLabel') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('PrintingDate') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('PrintingUser') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('validated_at') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('expire_at') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">' . $langs->trans('available_at') . '</th>';
        $content .= '<th class="wrapcolumntitle liste_titre">PDF</th>';
        $content .= '<th class="wrapcolumntitle liste_titre"></th>';
        $content .= '</tr>';
        while ($row = pg_fetch_assoc($res)) {
            $ticketNaploResults = getTicketnaploByTicketId($row['ticket_id']);
            $PDFButton = createPDFButton($id, $row['ticket_id']);
            $content .= '<tr class="oddeven">';
            $content .= '<td class="tdoverflowmax100">' . $row['ticket_id'] . '</td>';
            $content .= '<td class="tdoverflowmax200">' . $row['label'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $row['printing_date'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $row['lastname'] . ' ' . $row['firstname'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $row['validated_at'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $row['expire_at'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $row['available_at'] . '</td>';
            $content .= '<td class="tdoverflowmax100">' . $PDFButton . '</td>';
            $content .= '<td class="tdoverflowmax10 fa fa-chevron-down padding-left5" id="arrow_' . $row['ticket_id'] . '" onClick="myFunction(' . $row['ticket_id'] . ')" style="cursor:pointer;"></td>';
            $content .= '</tr>';
            $content .= '<tr id="hidden_' . $row['ticket_id'] . '" style="display:none;"><td colspan="7">';
            if (pg_num_rows($ticketNaploResults) == 0) {
                $content .= '<div style="width:100%; height:50px; margin-top:20px; text-align: center;">Nincs adat. A jegy még nem volt használva.</div>';
            } else {
                $content .= '<div style="width:100%; text-align: center; height:40px; margin-top:10px;">JEGYHASZNÁLAT</div>';
                $content .= '<table class="centpercent noborder listaction">';
                $content .= '<tr class="liste_titre">';
                $content .= '<th class="wrapcolumntitle liste_titre">Használat időpontja</th>';
                $content .= '<th class="wrapcolumntitle liste_titre">Eszköz</th>';
                $content .= '<th class="wrapcolumntitle liste_titre">Helyszín</th>';
                $content .= '<th class="wrapcolumntitle liste_titre">Státusz</th>';
                $content .= '</tr>';
                while ($result = pg_fetch_assoc($ticketNaploResults)) {
                    $deviceString = !is_null($result['device_name']) ? $result['device_name'] : 'Mobilephone';
                    $locationString = !is_null($result['location_name']) ? $result['location_name'] . '(' . $result['available_services'] . ')' : 'Validated by mobilephone';
                    $content .= '<tr class="oddeven">';
                    $content .= '<td class="tdoverflowmax100">' . $result['naplo_date_creation'] . '</td>';
                    $content .= '<td class="tdoverflowmax100">' . $deviceString . '</td>';
                    $content .= '<td class="tdoverflowmax100">' . $locationString . '</td>';
                    $content .= '<td class="tdoverflowmax100" style="color:' . setColor($result['status']) . ';">' . $statuses[$result['status']] . '</td>';
                    $content .= '</tr>';
                }
                $content .= '</table>';
            }
            $content .= '</td></tr>';
        }
        $content .= '</table>';
        print $content;

        print dol_get_fiche_end();
    } else {
        // Record not found
        print "ErrorRecordNotFound";
    }
}

// End of page
llxFooter();
$db->close();
?>
<link rel="stylesheet" type="text/css" href="/custom/bbus/views/bbus.css">
<script src="/custom/bbus/js/bbus.js"></script>;