<?php
include("../classes/manager.class.php");
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

$m = new Manager();
$output = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

extract($_REQUEST);

/* ------------------------------
   Date filters (default last 90d)
------------------------------- */
if (!isset($datefrom) || $datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-90 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if (!isset($dateto) || $dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$displayFrom = date("d-m-Y", strtotime($datefrom));
$displayTo   = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo   = date("Y-m-d", strtotime($dateto));

/* ------------------------------
   Build filter string
------------------------------- */
$filterP = " WHERE DATE_FORMAT(po_date,'%Y-%m-%d')>='$qryDate' AND DATE_FORMAT(po_date,'%Y-%m-%d')<='$qryTo' ";

/* Optional filters */
$status = isset($_GET['status']) ? trim($_GET['status']) : 'All';
if ($status !== '' && $status !== 'All') {
    $status = addslashes($status);
    $filterP .= " AND status = '$status' ";
}

$po_code = isset($_GET['po_code']) ? trim($_GET['po_code']) : '';
if ($po_code !== '') {
    $po_code = addslashes($po_code);
    $filterP .= " AND po_code LIKE '%$po_code%' ";
}

$billed_company = isset($_GET['billed_company']) ? trim($_GET['billed_company']) : '';
if ($billed_company !== '') {
    $billed_company = addslashes($billed_company);
    $filterP .= " AND billed_company LIKE '%$billed_company%' ";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        table{ font-size:18px; }
        .label { font-weight:bold; }
    </style>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Purchase Orders</h3>
            </div>
            <hr>

            <script>
                $(function () {
                    $('#datepicker1').pickadate({ format: 'dd-mm-yyyy', selectMonths: true, selectYears: true });
                    $('#datepicker2').pickadate({ format: 'dd-mm-yyyy', selectMonths: true, selectYears: true });
                });
            </script>

            <?php if (isset($_GET['view'])) { ?>
                <form action="" method="get" name="search" id="searchfrm">
                    <table class="table">
                        <tr>
                            <td class="col s3">PO Date From<br>
                                <input type="text" name="datefrom" id="datepicker1"
                                       placeholder="Date From"
                                       value="<?= $displayFrom ?>" class="datepicker form-control"/>
                                <input type="hidden" name="view" id="view" class="form-control"/>
                            </td>
                            <td class="col s3">PO Date To<br>
                                <input type="text" name="dateto" id="datepicker2"
                                       placeholder="Date To"
                                       value="<?= $displayTo ?>" class="datepicker form-control"/>
                            </td>
                            <td class="col s3">Status<br>
                                <?php
                                $statuses = ['All','draft','issued','closed','cancelled'];
                                ?>
                                <select class="form-control" id="status" name="status">
                                    <?php foreach ($statuses as $st): ?>
                                        <option value="<?= $st ?>" <?= ($st===$status?'selected':'') ?>><?= ucfirst($st) ?></option>
                                    <?php endforeach; ?>
                                </select><br/>
                            </td>
                            <td class="col s3">PO #<br>
                                <input type="text" name="po_code" value="<?= htmlspecialchars($po_code ?? '', ENT_QUOTES) ?>" />
                            </td>
                           <!-- <td class="col l2">Billed Company<br>
                                <input type="text" name="billed_company" value="<?= htmlspecialchars($billed_company ?? '', ENT_QUOTES) ?>" />
                            </td> -->
                          <tr>
                            <td class="col l2">
                                <button type="submit" class="btn waves-effect waves-light" style="float:left;">Search</button>
                            </td>
                      </tr>
                        </tr>
                    </table>
                </form>
                <hr>
            <?php } ?>

            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;"
                       href="purchase_order_create.php?add">Add
                        <i class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>

            <?php
            // -------- Listing (view) --------
            if (isset($_GET['view'])) {
            ?>
                <?php if (isset($_GET['sucess'])) { ?>
                    <div id='card-alert' class='card green lighten-5'>
                        <div class='card-content green-text'>
                            <p>Successfully updated!</p>
                        </div>
                        <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <?php if (isset($_GET['error'])) { ?>
                    <div id='card-alert' class='card orange lighten-5'>
                        <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Error occurred!</p>
                        </div>
                        <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>

                <div class="table-datatables">
                    <table id="data-table-tandard" class="responsive-table display">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>PO Date</th>
                            <th>PO #</th>
                            <th>Billed Company</th>
                          	<th>Shipped Company</th>
                            <th>Created By</th>
                            <th>Status</th>
                            <th style="text-align: right;">Total Qty</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>PO Date</th>
                            <th>PO #</th>
                            <th>Billed Company</th>
                            <th>Created By</th>
                            <th>Status</th>
                            <th style="text-align: right;">Total Qty</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = PurchaseOrder::GetPurchaseOrderList($filterP);
                        if ($qry) {
                            foreach ($qry as $row) { ?>
                                <tr>
                                    <td>
                                        <?php if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') { ?>
                                            <!-- Print -->
                                            <a href="report/print/purchase_order.php?id=<?= $row->id; ?>"
                                               target="_blank" title="Print PO">
                                                <span class="mini-stat-icon orange darken-2"
                                                      style="width:20px;height:20px;font-size:12px;line-height:20px;">
                                                    <i class="mdi-action-print"></i>
                                                </span>
                                            </a>
                                            <!-- View -->
                                            <a href="purchase_order.php?edit&id=<?= $row->id; ?>&v"
                                               title="View" style="margin-left:8px;">
                                                <span class="mini-stat-icon pink"
                                                      style="width:20px;height:20px;font-size:12px;line-height:20px;">
                                                    <i class="mdi-action-description"></i>
                                                </span>
                                            </a>
                                            <!-- Edit only if draft -->
                                            <?php if (strtolower($row->status) === 'draft') { ?>
                                                <a href="purchase_order_create.php?edit&id=<?= $row->id; ?>"
                                                   title="Edit" style="margin-left:8px;">
                                                    <span class="mini-stat-icon orange"
                                                          style="width:20px;height:20px;font-size:12px;line-height:20px;">
                                                        <i class="mdi-image-edit"></i>
                                                    </span>
                                                </a>
                                            <?php } ?>
                                        <?php } else { ?>
                                            <!-- Non-edit role: only view -->
                                            <a href="purchase_order.php?edit&id=<?= $row->id; ?>&v" title="View">
                                                <span class="mini-stat-icon pink"
                                                      style="width:20px;height:20px;font-size:12px;line-height:20px;">
                                                    <i class="mdi-action-description"></i>
                                                </span>
                                            </a>
                                        <?php } ?>
                                    </td>
                                    <td><?= date('d-m-Y', strtotime($row->po_date)); ?></td>
                                    <td><?= htmlspecialchars($row->po_code); ?></td>
                                    <td><?= htmlspecialchars(ucwords($row->billed_company)); ?></td>
                                  	<td><?= htmlspecialchars(ucwords($row->shipped_company)); ?></td>
                                    <td><?= htmlspecialchars($row->created_by_name); ?></td>
                                    <td><?= htmlspecialchars(ucwords($row->status)); ?></td>
                                    <td style="text-align:right;"><?= number_format((float)$row->total_quantity, 3); ?></td>
                                </tr>
                            <?php }
                        } ?>
                        </tbody>
                    </table>
                </div>
            <?php
            } // end list (view)

            /* ------------------------------
               Single record: view or edit mode
            ------------------------------- */
            if (isset($_GET['edit'])) {
                $id = (int)$_GET['id'];

                // View-only block (like your ?edit&id=&v pattern)
                if ($id && isset($_REQUEST['v'])) {
                    $h = PurchaseOrder::GetPurchaseOrderById($id);
                    if ($h) {
                        $items = PurchaseOrderItem::GetPurchaseOrderItemsByPO($id);
                        ?>
                        <div class="row">
                            <div class="col s12 form-group">
                                <div class="col s8">
                                    <div class="row">
                                        <div class="col s6 label">PO Date:</div>
                                        <div class="col s6"><?= date('d-m-Y', strtotime($h->po_date)); ?></div>
                                    </div>
                                    <div class="row">
                                        <div class="col s6 label">PO #:</div>
                                        <div class="col s6"><?= htmlspecialchars($h->po_code); ?></div>
                                    </div>
                                    <div class="row">
                                        <div class="col s6 label">Created By:</div>
                                        <div class="col s6"><?= htmlspecialchars($h->created_by_name); ?></div>
                                    </div>
                                    <div class="row">
                                        <div class="col s6 label">Status:</div>
                                        <div class="col s6"><?= htmlspecialchars(ucwords($h->status)); ?></div>
                                    </div>
                                    <div class="row">
                                        <div class="col s6 label">Billed Company:</div>
                                        <div class="col s6"><?= htmlspecialchars($h->billed_company); ?></div>
                                    </div>
                                    <?php if (!empty($h->remarks)) { ?>
                                    <div class="row">
                                        <div class="col s6 label">Remarks:</div>
                                        <div class="col s6"><?= nl2br(htmlspecialchars($h->remarks)); ?></div>
                                    </div>
                                    <?php } ?>

                                    <div class="row">
                                        <div class="col s12">
                                            <h5>Items</h5>
                                            <table class="striped bordered">
                                                <thead>
                                                <tr>
                                                    <th style="width:60px;">S.No</th>
                                                    <th>Item Detail</th>
                                                    <th style="width:140px;">Unit</th>
                                                    <th style="width:160px; text-align:right;">Quantity</th>
                                                </tr>
                                                </thead>
                                                <tbody>
                                                <?php
                                                $sn = 1;
                                                if ($items) {
                                                    foreach ($items as $it) { ?>
                                                        <tr>
                                                            <td style="text-align:center;"><?= $sn++; ?></td>
                                                            <td>
                                                                <div><b><?= htmlspecialchars($it->item_name); ?></b></div>
                                                                <?php if (!empty($it->item_desc)) { ?>
                                                                    <div><?= htmlspecialchars($it->item_desc); ?></div>
                                                                <?php } ?>
                                                            </td>
                                                            <td><?= htmlspecialchars($it->unit); ?></td>
                                                            <td style="text-align:right;"><?= number_format((float)$it->quantity, 3); ?></td>
                                                        </tr>
                                                    <?php }
                                                } ?>
                                                <tr>
                                                    <td colspan="3" style="text-align:right;"><b>Total Quantity</b></td>
                                                    <td style="text-align:right;"><b><?= number_format((float)$h->total_quantity, 3); ?></b></td>
                                                </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                    <div class="row" style="margin-top:10px;">
                                        <div class="col s12">
                                            <a class="btn" href="report/print/purchase_order.php?id=<?= $id; ?>" target="_blank">
                                                <i class="mdi-action-print left"></i> Print
                                            </a>
                                            <a class="btn" href="purchase_order.php?view">Back</a>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <?php
                    } else {
                        echo "No data found.";
                    }
                } // end view-only block
            } // end edit gate
            ?>
        </div>
    </div>
</div>
<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            var btn = $(this);
            btn.hide();
            setTimeout(function () { btn.show(); }, fewSeconds * 1000);
        });

        if ($.fn.DataTable.isDataTable('#data-table-tandard')) {
            $('#data-table-tandard').DataTable().destroy();
        }
        $('#data-table-tandard').DataTable({
            "ordering": false
        });
    });
</script>
</body>
</html>
