<?php
$rnd = rand();
$printArea = "printArea" . $rnd;
$btnPrint = "btnPrint" . $rnd;
$btnExport = "btnExport" . $rnd;

include('includes/function.php');
/**
 * export to excel
 */
$filename="public/report/abc_analysis_" . $this->Session->id(session_id()) . ".csv";
$fp=fopen($filename,"wb");
$excelContent = '';
?>
<script type="text/javascript">
    $(document).ready(function(){
        $("#<?php echo $btnPrint; ?>").click(function(){
            w=window.open();
            w.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
            w.document.write('<link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/style.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/table.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/button.css" /><link rel="stylesheet" type="text/css" href="<?php echo $this->webroot; ?>css/print.css" media="print" />');
            w.document.write($("#<?php echo $printArea; ?>").html());
            w.document.close();
            w.print();
            w.close();
        });

        $("#<?php echo $btnExport; ?>").click(function(){
            window.open("<?php echo $this->webroot; ?>public/report/inventory_activity_with_global_detail_<?php echo $this->Session->id(session_id()); ?>.csv", "_blank");
        });
    });
</script>
<div id="<?php echo $printArea; ?>">
    <?php
    $msg = '<b style="font-size: 18px;">' . MENU_REPORT_FSN_ANALYSIS . '</b><br /><br />';
    $excelContent .= MENU_REPORT_ABC_ANALYSIS."\n\n";
    $condition = '';
    if($_POST['date_from']!='') {
        $msg .= REPORT_FROM.': '.$_POST['date_from'];
        $excelContent .= REPORT_FROM.': '.$_POST['date_from'];
        $condition .= "inv_date.date >= '".dateConvert($_POST['date_from'])."'";
    }
    if($_POST['date_to']!='') {
        $msg .= ' '.REPORT_TO.': '.$_POST['date_to'];
        $excelContent .= ' '.REPORT_TO.': '.$_POST['date_to'];
        $condition .= " AND inv_date.date <= '".dateConvert($_POST['date_to'])."'";
    }
    $msg .= '<br /><br />';
    $excelContent .= "\n\n";
    echo $this->element('/print/header-report',array('msg'=>$msg));
    // Total Begin Balance
    $fsnAvgs  = array();
    $fsnCons  = array();
    $fsnFinal = array();
    $totalAvg = 0;
    $totalCon = 0;
    $totalItems = 0;
    $dateFrom   = dateConvert($_POST['date_from']);
    $dateTo     = dateConvert($_POST['date_to']);
    $dayDiff  = getDays($dateFrom, $dateTo);
    $sqlFsn   = mysql_query("SELECT products.id AS product_id, products.code AS code, products.name AS name, SUM(inv_date.total_pb) AS totalRec, SUM(((inv_date.total_so + inv_date.total_pos) - inv_date.total_cm)) AS totalSales, SUM(inv_date.total_ending) AS totalEnd FROM inventory_total_by_dates AS inv_date INNER JOIN products ON products.id = inv_date.product_id WHERE ".$condition." GROUP BY inv_date.product_id;");
    $i = 0;
    if(mysql_num_rows($sqlFsn)){
        $totalItems = mysql_num_rows($sqlFsn);
        while($rowFsn = mysql_fetch_array($sqlFsn)){
            $totalBegin = 0;
            $avgStay  = 0;
            $consRate = 0;
            $sqlBg = mysql_query("SELECT total_ending FROM inventory_total_by_dates WHERE date <= '".dateConvert($_POST['date_from'])."' AND product_id = ".$rowFsn['product_id']." ORDER BY date DESC LIMIT 1;");
            if(mysql_num_rows($sqlBg)){
                $rowBg = mysql_fetch_array($sqlBg);
                $totalBegin = $rowBg[0];
            }
            if($rowFsn['totalEnd'] > 0){
                $avgStay  = $rowFsn['totalEnd'] / ($totalBegin + $rowFsn['totalRec']);
            }
            if($rowFsn['totalSales'] > 0){
                $consRate = $rowFsn['totalSales'] / $dayDiff;
            }
            // AVG Stay
            $fsnAvgs[$i]['pid']  = $rowFsn['product_id'];
            $fsnAvgs[$i]['code'] = $rowFsn['code'];
            $fsnAvgs[$i]['name'] = $rowFsn['name'];
            $fsnAvgs[$i]['avg_stay'] = $avgStay;
            $totalAvg += $avgStay>0?$avgStay:1;
            // Cons Rate
            $fsnCons[$i]['pid']  = $rowFsn['product_id'];
            $fsnCons[$i]['code'] = $rowFsn['code'];
            $fsnCons[$i]['name'] = $rowFsn['name'];
            $fsnCons[$i]['con_rate'] = $consRate;
            $totalCon += $consRate;
            $i++;
        }
    }
    // (%) Avg Stay
    $j=0;
    foreach($fsnAvgs AS $fsnAvg){
        if($fsnAvg['avg_stay'] == 0){
            $fsnAvgs[$j]['avg_percent'] = 0;
        } else {
            $fsnAvgs[$j]['avg_percent'] = $fsnAvg['avg_stay'] * 100 / $totalAvg;
        }
        $j++;
    }
    // (%) Cons Rate
    $k=0;
    foreach($fsnCons AS $fsnCon){
        if($fsnCon['con_rate'] == 0){
            $fsnCons[$k]['con_percent'] = 0;
        } else {
            $fsnCons[$k]['con_percent'] = $fsnCon['con_rate'] * 100 / $totalCon;
        }
        $k++;
    }
    // Sort
    arraySortBy('avg_percent', $fsnAvgs, 'asc');
    arraySortBy('con_percent', $fsnCons, 'asc');
    ?>
    <table cellpadding="5" cellspacing="0" class="table">
        <tr>
            <th class="first"><?php echo TABLE_SKU; ?></th>
            <th><?php echo TABLE_NAME; ?></th>
            <th><?php echo 'Average Stay'; ?></th>
            <th><?php echo 'Cumulative Avg Stay'; ?></th>
            <th><?php echo '(%) Average Stay'; ?></th>
            <th><?php echo 'Category'; ?></th>
        </tr>
        <?php
        $cumulativeAvg = 0;
        $avgPercent = 0;
        $loop = 1;
        foreach($fsnAvgs AS $fsnAvg){
            $cumulativeAvg += $fsnAvg['avg_stay'];
            $avgPercent += $fsnAvg['avg_percent'];
        ?>
        <tr>
            <td class="first"><?php echo $fsnAvg['code']; ?></td>
            <td><?php echo $fsnAvg['name']; ?></td>
            <td><?php echo number_format($fsnAvg['avg_stay'], 2); ?></td>
            <td><?php echo number_format($cumulativeAvg, 2); ?></td>
            <td><?php echo number_format($avgPercent, 2); ?></td>
            <td>
                <?php
                if($avgPercent <= 40){
                    echo $category = 'N';
                } else if($avgPercent <= 70){
                    echo $category = 'S';
                } else {
                    echo $category = 'F';
                }
                ?>
            </td>
        </tr>
        <?php
            $fsnFinal[$fsnAvg['pid']]['code'] = $fsnAvg['code'];
            $fsnFinal[$fsnAvg['pid']]['name'] = $fsnAvg['name'];
            $fsnFinal[$fsnAvg['pid']]['avgs'] = $category;
            $loop++;
        }
        ?>
    </table>
    <table cellpadding="5" cellspacing="0" class="table">
        <tr>
            <th class="first"><?php echo TABLE_SKU; ?></th>
            <th><?php echo TABLE_NAME; ?></th>
            <th><?php echo 'Cons Rate'; ?></th>
            <th><?php echo 'Cumulative Cons Rate'; ?></th>
            <th><?php echo '(%) Cons Rate'; ?></th>
            <th><?php echo 'Category'; ?></th>
        </tr>
        <?php
        $cumulativeCon = 0;
        $ratePercent   = 0;
        foreach($fsnCons AS $fsnCon){
            $cumulativeCon += $fsnCon['con_rate'];
            $ratePercent += $fsnCon['con_percent'];
        ?>
        <tr>
            <td class="first"><?php echo $fsnCon['code']; ?></td>
            <td><?php echo $fsnCon['name']; ?></td>
            <td><?php echo number_format($fsnCon['con_rate'], 2); ?></td>
            <td><?php echo number_format($cumulativeCon, 2); ?></td>
            <td><?php echo number_format($ratePercent, 2); ?></td>
            <td>
                <?php
                if($ratePercent <= 40){
                    echo $category = 'N';
                } else if($ratePercent <= 70){
                    echo $category = 'S';
                } else {
                    echo $category = 'F';
                }
                ?>
            </td>
        </tr>
        <?php
            $fsnFinal[$fsnCon['pid']]['code'] = $fsnCon['code'];
            $fsnFinal[$fsnCon['pid']]['name'] = $fsnCon['name'];
            $fsnFinal[$fsnCon['pid']]['cons'] = $category;
        }
        ?>
    </table>
    <table cellpadding="5" cellspacing="0" class="table">
        <tr>
            <th class="first"><?php echo TABLE_SKU; ?></th>
            <th><?php echo TABLE_NAME; ?></th>
            <th><?php echo 'FSN(Cons)'; ?></th>
            <th><?php echo 'FSN(Avg)'; ?></th>
            <th><?php echo 'Final FSN'; ?></th>
        </tr>
        <?php
        foreach($fsnFinal AS $final){
        ?>
        <tr>
            <td class="first"><?php echo $final['code']; ?></td>
            <td><?php echo $final['name']; ?></td>
            <td><?php echo $final['cons']; ?></td>
            <td><?php echo $final['avgs']; ?></td>
            <td>
                <?php
                if($final['cons'] == 'N' && $final['avgs'] == 'N'){
                    echo $category = 'N';
                } else if($final['cons'] == 'S' && $final['avgs'] == 'S'){
                    echo $category = 'S';
                } else if($final['cons'] == 'F' && $final['avgs'] == 'F'){
                    echo $category = 'F';
                } else if($final['cons'] == 'N' && $final['avgs'] == 'S'){
                    echo $category = 'N';
                } else if($final['cons'] == 'N' && $final['avgs'] == 'F'){
                    echo $category = 'S';
                } else if($final['cons'] == 'S' && $final['avgs'] == 'N'){
                    echo $category = 'N';
                } else if($final['cons'] == 'S' && $final['avgs'] == 'F'){
                    echo $category = 'S';
                } else if($final['cons'] == 'F' && $final['avgs'] == 'N'){
                    echo $category = 'S';
                } else if($final['cons'] == 'F' && $final['avgs'] == 'S'){
                    echo $category = 'F';
                }
                ?>
            </td>
        </tr>
        <?php
        }
        ?>
    </table>
</div>