<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = '';
$dateto = '';
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
if (isset($_POST) && !empty($_GET['validate'])) {
    $data['status'] = 'Pending';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($_GET['validate'], $data);
    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}

if (isset($_POST) && !empty($_GET['cancel'])) {
    $invoiceId = $_GET['cancel'];
    
    // Retrieve original stock deductions for the invoice
    $original_deductions = ProductStockDeductions::GetProductStockDeductionByInvoiceId($invoiceId);
    
    // Restore the deducted stock quantities in FIFO order
  
  

    foreach ($original_deductions as $deduction) {
      
          $produced_product_data = ProducedProducts::GetProducedProductById($deduction->produced_product_id);

       $current_remaining_quantity = $produced_product_data->remaining_quantity ;
       $updated_remaining_quantity = $current_remaining_quantity + $deduction->deducted_quantity;
      
      $used_quantity = $produced_product_data->used_quantity;
      $reverse_quantity = $used_quantity - $deduction->deducted_quantity;
      
    	
      
      ProducedProducts::UpdateProducedProduct($deduction->produced_product_id,['remaining_quantity' => $updated_remaining_quantity,'used_quantity' => $reverse_quantity ]);

    }
    
    // Delete the original deduction records
    ProductStockDeductions::DeleteProductStockDeductionByInvoiceId($invoiceId);

    // Mark the invoice as canceled
    $data['status'] = 'Cancel';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($_GET['cancel'], $data);

    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}


if (isset($_POST) && !empty($_GET['paid'])) {
    $data['status'] = 'Paid';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($_GET['paid'], $data);
    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("d-m-Y", strtotime($datefrom));
$dateto = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));
$filter = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel' ";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        .fa-credit-card:before, .fa-edit:before, .fa-pencil-square-o:before, .fa-check-circle:before, .fa-check-square-o:before, .fa-arrows-alt:before {
            margin-right: 3px;
        }
        table{
            font-size: 18px;
        }
    </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>Invoices</h3>
            </div>

            <script>
                $(function () {
                    $('.datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                    });
                    $('.datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col l4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="datepicker form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col l4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="datepicker form-control"/>
                        </td>
                        <td class="col l4">&nbsp;<br>
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;"
                       href="invoice_create.php?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            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-simple" class="responsive-table display">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Code</th>
                            <th>Customer</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Amount</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Code</th>
                            <th>Customer</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Amount</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = Invoice::GetInvoiceList($filter);
                        if ($qry) {
                            foreach ($qry as $qery) { ?>
                                <tr>
                                    <td>
                                        <?php
                                        if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') {
                                            ?>
                                            <?php if ($qery->status != 'Cancel') {
                                        if ($_SESSION['clone'] == 1) {
                                            $inv = 'invoicetax';
                                        }else{
                                            $inv = 'invoice';
                                        }
                                            ?>
                                            <a href="print/<?=$inv?>.php?id=<?php echo $qery->id; ?>"
                                               target="_blank" title="Print Invoice">
                                                                    <span
                                                                        style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon orange darken-2"><i
                                                                            class="mdi-action-print"></i></span>
                                            </a>
                                        <?php }
                                        if ($qery->status == 'Pending' || $qery->status == 'Draft') { ?>
                                            <a href="invoice_create.php?edit&id=<?php echo $qery->id; ?>"
                                               title="Edit">
                                                                    <span
                                                                        style="width: 50px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon yellow darken-2">Edit</span></a>
                                        <?php }
                                        if ($qery->status == 'Pending') { ?>
                                            <a href="payment_create.php?add&ref=<?php echo $qery->id; ?>"
                                               title="Payment">
                                                                    <span
                                                                        style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon green darken-2">Payment</span>
                                            </a>
                                        <br>
                                            <div class="clearfix"></div>

                                            <a style="margin-left:30px; display: block; cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Paid">
                                                <span
                                                    style="width: 50px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-paid<?= $qery->id ?> mini-stat-icon cyan darken-2">Paid</span>
                                            </a>
                                            <script>
                                                $('.btn-warning-paid<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "You will not be able to change the status again",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been paid!", "success");
                                                            window.location.href = 'invoice.php?paid=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>

                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Cancel">
                                                                    <span
                                                                        style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="btn-warning-cancel<?= $qery->id ?> mini-stat-icon deep-orange darken-3">Cancel</span>
                                            </a>
                                        <?php
                                        $PaymentCode[] = '';
                                        $PaymentCodes = '';
                                        $CancelPayment = '';
                                        $filterPaymentCancel = " WHERE invoice_reference_code = '$qery->id' AND status <> 'Cancel' ";
                                        $CancelPayment = Payment::GetPaymentList($filterPaymentCancel);
                                        if ($CancelPayment) {
                                            foreach ($CancelPayment AS $CancelPaymentRow) {
                                                $PaymentCode[] = $CancelPaymentRow->code;
                                            }
                                            $PaymentCodes = implode(',', $PaymentCode);
                                        }
                                        if (!$PaymentCodes) { ?>
                                            <script>
                                                $('.btn-warning-cancel<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure change status to cancel?<br>You will not be able to change the status again <br><?php if ($PaymentCodes) {echo '<p>Please delete payments ' . $PaymentCodes . ' against this invoice</p>';}?>",
                                                            type: "warning",
                                                            html: true,
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been cancelled!", "success");
                                                            window.location.href = 'invoice.php?cancel=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>
                                        <?php }else{ ?>
                                            <script>
                                                $('.btn-warning-cancel<?= $qery->id ?>').click(function () {
                                                    swal({
                                                        title: "Are you sure?",
                                                        text: "Are you sure change status to cancel?<br>You will not be able to change the status again <br><?php if ($PaymentCodes) {echo '<p>Please delete payments ' . $PaymentCodes . ' against this invoice</p>';}?>",
                                                        type: "error",
                                                        html: true,
                                                        confirmButtonColor: '#DD6B55',
                                                        closeOnConfirm: false
                                                    });
                                                });
                                            </script>
                                        <?php }
                                        } else if ($qery->status == 'Draft') { ?>
                                            <!-- Trigger the modal with a button -->
                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Validate">
                                                <span
                                                    style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-val<?= $qery->id ?> mini-stat-icon orange">Validate</span>
                                            </a>
                                            <script>
                                                $('.btn-warning-val<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure you want to validate?",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your invoice has been validated!", "success");
                                                            window.location.href = 'invoice.php?validate=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>
                                        <?php }
                                        /*else if($qery->status == 'Paid') { ?>
                                            <label>
                                                <span style="width: 50px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;" class="mini-stat-icon tar"><i class="fa fa-check-square-o" title="Paid">Paid</i></span>
                                            </label>
                                        <?php } else if($qery->status == 'Cancel') { ?>
                                            <label>
                                                <span style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;" class="mini-stat-icon orange-theme"><i class="fa fa-arrows-alt" title="Cancel">Cancel</i></span>
                                            </label>
                                        <?php }*/ ?>
                                        <?php } else { ?>
                                            <a href="?edit&id=<?php echo $qery->id; ?>&v"
                                               title="View"><i
                                                    class="fa fa-file-text"></i></a>
                                        <?php } ?>
                                    </td>
                                    <td><?php echo $qery->create_date; ?></td>
                                    <?php
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                    ?>
                                    <td><?php echo $qery->code; ?></td>
                                    <td><?php echo $customer->name; ?></td>
                                    <td><?php echo $salesPerson->username; ?></td>
                                    <td><?php echo $qery->status; ?></td>
                                    <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php
            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>

<?php include('../includes/inc_js.php'); ?>
</body>
</html>