<?php

session_start();

require('../lib/dbclass.php');




require('../PhpXlsxGenerator.php') ;


// Filter the excel data
function filterData(&$str)
{
    $str = preg_replace("/\t/", '\\t', $str);
    $str = preg_replace("/\r?\n/", '\\n', $str);

    if (strstr($str, '"')) {
        $str = '"' . str_replace('"', '""', $str) . '"';
    }
}

// Excel file name for download
$fileName = 'Ward Consolidated Details.xlsx';

// Column names
$excelData[] = ['Name','Product','Qty'];



$chlngid = $_SESSION['challengeid'];


$data = findQuery("SELECT tbl_ward.ward_name,tbl_transactiondetails.item,sum(tbl_transactiondetails.qty) qty FROM `tbl_transaction` inner join tbl_customer on tbl_customer.id=tbl_transaction.customerid

inner join tbl_ward on tbl_ward.id=tbl_customer.Ward
inner join tbl_transactiondetails on tbl_transactiondetails.hdrid=tbl_transaction.id
where tbl_transaction.challengeid=$chlngid and tbl_transaction.donation=0 and tbl_transaction.sponsorship=0 and tbl_transaction.clubid=0    group by tbl_ward.ward_name,tbl_transactiondetails.item order by ward_name");

$name = '';

if ($data) {
    // Output each row of the data
    foreach ($data as $index => $row) {
        $item = $row['item'];

        $datae = findQuery("select * from  `tbl_challenge` where id=$chlngid");


        if ($datae) {
            $prod1 = 0;
            $prod2 = 0;
            $prod3 = 0;

            $qty1 = 0;
            $qty2 = 0;
            $qty3 = 0;

            $product1  = '';
            $product2  = '';
            $product3  = '';
            $Ordrdqty1 = 0;
            $Ordrdqty2 = 0;
            $Ordrdqty3 = 0;



            if ($item == 1) {
                $prod1 = 1;
                $qty1  = $row['qty'];
            } elseif ($item == 2) {
                $prod2 = 2;
                $qty2  = $row['qty'];
            } else {
                $prod3 = 3;
                $qty3  = $row['qty'];
            }





            if ($prod1 == 1) {
                $product  = $datae[0]['product_name1'];
                $Ordrdqty = $qty1;
            }

            if ($prod2 == 2) {
                $product  = $datae[0]['product_name2'];
                $Ordrdqty = $qty2;
            }

            if ($prod3 == 3) {
                $product  = $datae[0]['product_name3'];
                $Ordrdqty = $qty3;
            }
        }

        if ($name == $row['ward_name']) {
            $row['ward_name'] = '';
        }
        $lineData = [
                        $row['ward_name'],
                        $product,
                        $Ordrdqty,
                        ];
        $excelData[] = $lineData;


        $name = $row['ward_name'];
    }
} else {
    $excelData .= 'No records found...' . "\n";
}

// Export data to excel and download as xlsx file
$xlsx = CodexWorld\PhpXlsxGenerator::fromArray($excelData);
$xlsx->downloadAs($fileName);

exit;
