<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$amount = '';
$description = '';

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

if (isset($_POST) && !empty($_GET['delete'])) {
    ExpenseMartSetup::DeleteExpenseMartSetup($_GET['delete']);
    header("Location: " . PROJECT_ADMIN_URL . "expense_mart_setup.php?view");
    exit();
}


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));

//$filterE = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' ";
$filterE = " WHERE DATE_FORMAT(date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(date,'%Y-%m-%d')<='$qryTo' ";
$filterE .= " ORDER BY `date` DESC, `id` DESC ";

//if($_SESSION['sess_type'] == 'profile'){
//	$uid = $_SESSION['sess_userid'];
//	$filterE .= " and user_id = '$uid' ";	
//}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        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>Cash In</h3>
            </div>
            <hr>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                    $('#datepicker2').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                  $('#datepicker3').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 l4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker1"
                                   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="datepicker2"
                                   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>
                          
                          <a href="petty_cash_in_multi_voucher_print.php?<?= http_build_query($_GET) ?>"
   target="_blank"
   class="btn waves-effect waves-light" style="margin-left:10px;">
   Print Vouchers
</a>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
          <?php endif; ?>
            
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
if (isset($_GET['add'])) {
    if (empty($date)) {
        $date = date('Y-m-d');
    }

     if (isset($_POST) && !empty($_POST)) {
      
        // Safely extract values from POST
        $date = isset($_POST['date']) ? $_POST['date'] : '';
        $amount = isset($_POST['amount']) ? $_POST['amount'] : '';
        $chq_date = isset($_POST['chq_date']) ? $_POST['chq_date'] : '';
        $chq_no = isset($_POST['chq_no']) ? $_POST['chq_no'] : '';
        $bank_id = isset($_POST['bank_id']) ? $_POST['bank_id'] : '';
        $description = isset($_POST['description']) ? $_POST['description'] : '';
        $created_by = isset($_SESSION['sess_userid']) ? $_SESSION['sess_userid'] : 0;

        $data = array();
        $data['date'] = date('Y-m-d H', strtotime($date));
        $data['amount'] = floatval($amount);
        $data['chq_date'] = !empty($chq_date) ? date('Y-m-d', strtotime($chq_date)) : null;
        $data['chq_no'] = $chq_no;
        $data['bank_id'] = $bank_id;
        $data['description'] = $description;
        $data['created_by'] = $created_by;
        $data['create_date'] = date('Y-m-d H:i:s');

        $errors = array();

        // Validation
        if (empty($amount) || floatval($amount) <= 0) {
            $errors[] = "Please enter a valid amount.";
        }

        if (empty($date)) {
            $errors[] = "Please select a date.";
        }

        if (count($errors) == 0) {
            // Ensure you define this method in your model class
            $q = PettyCashIn::AddPettyCashIn($data);

            if ($q) {
                $output = '';
                echo "<script>window.location.href='?view&success';</script>";
                exit;
            } else {
                $output = '<div class="alert alert-danger">Failed to add record. Try again.</div>';
            }
        } else {
            // Show validation errors
            $output = '<div class="alert alert-danger"><ul>';
            foreach ($errors as $error) {
                $output .= "<li>$error</li>";
            }
            $output .= '</ul></div>';
        }
    }

?>

           
                <div class="row">
                    <form action="" method="post" id="expense_mart_setup_form" novalidate="novalidate">
                        <div class="col-sm-12 form-group">
                            <?php echo $output; ?>
                            <div class="col-sm-8">
                                <div class="row">
                                    <span>(*) Mark Fields are mandatory</span><br/><br/>
                                </div>
                             
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="datepicker" name="date"
       										value="<?php echo !empty($date) && strtotime($date) ? date('d-m-Y', strtotime($date)) : date('d-m-Y'); ?>" />

                                        <label for="datepicker" class="control-label">Date *</label>
                                    </div>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="amount" maxlength="250"
                                               name="amount"
                                               value='<?php echo $amount; ?>'/>
                                        <label for="amount" class="control-label">Amount *</label>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                    <div class="input-field col s12">
                                       <input class="form-control" type="text" id="datepicker3" name="chq_date"
       										value="<?php echo !empty($chq_date) && strtotime($chq_date) ? date('d-m-Y', strtotime($chq_date)) : date('d-m-Y'); ?>" />

                                        <label for="datepicker1" class="control-label">CHQ Date *</label>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="chq_no" maxlength="250"
                                               name="chq_no"
                                               value='<?php echo $chq_no; ?>'/>
                                        <label for="chq_no" class="control-label">CHQ No *</label>
                                    </div>
                                </div>
                              
                                 <div class="row margin">
                                    <div class="input-field col s12">
                                        <select class="form-control" name="bank_id" id="bank_id">
                                            <?php
                                            $expenseCatFilter = "";
                                            $bankList = BankSetup::GetBankSetupList();
                                            if ($bankList) {
                                                foreach ($bankList as $bankListRow) {
                                                    $id = is_array($bankListRow) ? $bankListRow['id'] : $bankListRow->id;
                                                    $name = is_array($bankListRow) ? $bankListRow['bank_name'] : $bankListRow->bank_name;
                                                    $accountNo = is_array($bankListRow) ? $bankListRow['bank_account_number'] : $bankListRow->bank_account_number;

                                                    echo '<option value="' . $id . '" data-account="' . htmlspecialchars($accountNo) . '"';
                                                    if ($id == $bank_id) {
                                                        echo ' selected';
                                                    }
                                                    echo '>' . ucwords($name) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                        <label for="bank_id" class="control-label">Bank</label>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                <div class="input-field col s12">
                                  <input type="text" class="form-control" name="account_number" id="account_number" readonly>
                                  <label for="account_number" class="control-label">Bank Account No</label>
                                </div>
                              </div>



                              
                              
                              
                                <div class="row margin">
                                    <div class="input-field col s12">
                                <textarea class="materialize-textarea" name="description"
                                          id="description"><?php echo $description; ?></textarea>
                                        <label for="description" class="control-label">Description </label>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                  <div class="input-field col s12">
                                      <!-- Visible read-only username -->
                                      <input class="form-control" type="text" id="sales_person"
                                             name="sales_person" readonly
                                             value="<?php echo htmlspecialchars($_SESSION['sess_username']); ?>" />

                                      <!-- Hidden field for user ID -->
                                      <input type="hidden" id="sales_person_id"
                                             name="sales_person_id"
                                             value="<?php echo intval($_SESSION['sess_userid']); ?>" />

                                      <label for="sales_person" class="control-label">Sales Person *</label>
                                  </div>
                              </div>

                              
                              
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit
                                        </button>
                                        <button type="button" class="btn waves-effect waves-light"
                                                onclick="location.href='petty_cash_in.php?view'">Cancel
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <?php
      }       // add close
        
            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 style="text-align: right;">Amount</th>
                                  <th>CHQ Date</th>
                                  <th>CHQ No</th>
                                  <th>Bank</th>
                                  <th>Account #</th>
                                  <th>Description</th>
                                  <th>Sales Person</th>
                              </tr>
                          </thead>
                          <tfoot>
                              <tr>
                                  <th>Action</th>
                                  <th>Date</th>
                                  <th style="text-align: right;">Amount</th>
                                  <th>CHQ Date</th>
                                  <th>CHQ No</th>
                                  <th>Bank</th>
                                  <th>Account #</th>
                                  <th>Description</th>
                                  <th>Sales Person</th>
                              </tr>
                          </tfoot>
                        <tbody>
                         <?php
             // 	$sortByDateAndId = " ORDER BY `date` DESC, `id` DESC ";
                $qry = PettyCashIn::GetPettyCashInList($filterE);
                if ($qry) {
                    foreach ($qry as $qery) {
                        // Get bank info
                        $bankInfo = BankSetup::GetBankSetupById($qery->bank_id);
                        $bankName = $bankInfo ? $bankInfo->bank_name : '';
                        $bankAccount = $bankInfo ? $bankInfo->bank_account_number : '';

                        // Get user name
                        $user = User_setup::GetUserSetupId($qery->created_by);
                      //	print_r($user);
                      $username = ($user && isset($user->username)) ? ucwords($user->username) : 'Unknown';

                        ?>
                        <tr>
                           <td>
    <a href='?edit&id=<?php echo $qery->id; ?>' title="Edit">
        <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
              class="mini-stat-icon orange">
            <i class="mdi-image-edit"></i>
        </span>
    </a>
                             <!-- Print Voucher -->
  <a href="petty_cash_in_voucher_print.php?id=<?= (int)$qery->id ?>"
     title="Print Voucher" target="_blank">
    <span style="width:20px;height:20px;font-size:12px;line-height:20px;"
          class="mini-stat-icon green">
      <i class="mdi-action-description"></i>
    </span>
  </a>
</td>
                            <td data-order="<?php echo $qery->date; ?>">
    <?php echo date('d-m-Y', strtotime($qery->date)); ?>
</td>

                            <td style="text-align: right;"><?php echo number_format($qery->amount, 2); ?></td>
                            <td><?php echo $qery->chq_date ? date('d-m-Y', strtotime($qery->chq_date)) : '-'; ?></td>
                            <td><?php echo $qery->chq_no; ?></td>
                            <td><?php echo ucwords($bankName); ?></td>
                            <td ><?php echo $bankAccount; ?></td>
                            <td><?php echo nl2br(htmlspecialchars($qery->description)); ?></td>
                            <td><?php echo $username; ?></td>
                        </tr>
                        <?php
                    }
                }
                ?>
            </tbody>
        </table>
                </div>
                <?php

            } // close view


          if (isset($_GET['edit']) && !empty($_POST)) {
    extract($_REQUEST);
    $id = $_GET['id'];

    $data['date'] = date('Y-m-d', strtotime($date));
    $data['amount'] = $amount;
    $data['chq_date'] = date('Y-m-d', strtotime($chq_date));
    $data['chq_no'] = $chq_no;
    $data['bank_id'] = $bank_id;
    $data['description'] = $description;
    $data['created_by'] = $_SESSION['sess_userid'];

    $errors = [];
    if ($amount == 0) $errors[] = "Please enter amount";

    if (count($errors) === 0) {
        $q = PettyCashIn::UpdatePettyCashIn($id, $data);
        if ($q) {
            echo "<script>window.location.href='?view&sucess'</script>";
        } else {
            echo "<div class='card orange lighten-5'><div class='card-content orange-text'><p><strong>Error:</strong> Update failed!</p></div></div>";
        }
    } else {
        foreach ($errors as $val) {
            echo "<div class='card orange lighten-5'><div class='card-content orange-text'><p><strong>Warning:</strong> $val</p></div></div>";
        }
    }
}

if (isset($_GET['edit'])) {
    $id = $_GET['id'];
    if (empty($_POST)) {
        $qry = PettyCashIn::GetPettyCashInById($id);
        $date = $qry->date;
        $amount = $qry->amount;
        $chq_date = $qry->chq_date;
        $chq_no = $qry->chq_no;
        $bank_id = $qry->bank_id;
        $description = $qry->description;
    }
?>
<div class="row">
    <form action="?edit&id=<?php echo $id ?>" method="post" id="petty_cash_in_form" novalidate="novalidate">
        <div class="col-sm-12 form-group">
            <div class="col-sm-8">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input type="text" class="form-control" id="datepicker" name="date"
                               value="<?php echo date('d-m-Y', strtotime($date)); ?>" />
                        <label for="datepicker" class="control-label">Date *</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <input type="text" class="form-control" name="amount" id="amount"
                               value="<?php echo $amount; ?>" />
                        <label for="amount" class="control-label">Amount *</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <input type="text" class="form-control" id="datepicker3" name="chq_date"
                               value="<?php echo date('d-m-Y', strtotime($chq_date)); ?>" />
                        <label for="datepicker1" class="control-label">CHQ Date *</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <input type="text" class="form-control" name="chq_no" id="chq_no"
                               value="<?php echo $chq_no; ?>" />
                        <label for="chq_no" class="control-label">CHQ No *</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <select class="form-control" name="bank_id" id="bank_id">
                            <?php
                            $bankList = BankSetup::GetBankSetupList();
                            if ($bankList) {
                                foreach ($bankList as $bank) {
                                    $idb = is_array($bank) ? $bank['id'] : $bank->id;
                                    $name = is_array($bank) ? $bank['bank_name'] : $bank->bank_name;
                                    echo "<option value='$idb'" . ($idb == $bank_id ? " selected" : "") . ">" . ucwords($name) . "</option>";
                                }
                            }
                            ?>
                        </select>
                        <label for="bank_id" class="control-label">Bank</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <textarea class="materialize-textarea" name="description" id="description"><?php echo $description; ?></textarea>
                        <label for="description" class="control-label">Description</label>
                    </div>
                </div>
                <div class="row margin">
                    <div class="input-field col s12">
                        <button type="submit" class="btn waves-effect waves-light">Update</button>
                        <button type="button" class="btn waves-effect waves-light" onclick="location.href='?view'">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
          <?php 
            }
            ?>
        </div>
    </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 () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });
  
  document.addEventListener('DOMContentLoaded', function () {
    const bankDropdown = document.getElementById('bank_id');
    const accountField = document.getElementById('account_number');

    bankDropdown.addEventListener('change', function () {
        const selectedOption = this.options[this.selectedIndex];
        const accountNumber = selectedOption.getAttribute('data-account');
        accountField.value = accountNumber || '';
    });

    // Trigger change on page load to prefill if selected
    bankDropdown.dispatchEvent(new Event('change'));
});
</script>
</body>
</html>