<?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();
}

/** ---------- Defaults ---------- */
$mode = (isset($_GET['edit']) ? 'edit' : 'add');
$id   = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$po_code         = '';
$po_date_display = '';
// ...
if ($mode === 'add' && empty($po_date_display)) {
  $po_date_display = date('d-m-Y'); // show today on first load
}
$created_by_name = $_SESSION['sess_username'] ?? '';
$status          = 'draft';

$billed_company  = '';
$billed_contact  = '';
$billed_phone    = '';
$billed_email    = '';
$billed_ntn      = '';
$billed_strn     = '';
$billed_address  = '';

$shipped_company = '';
$shipped_contact = '';
$shipped_phone   = '';
$shipped_email   = '';
$shipped_ntn     = '';
$shipped_strn    = '';
$shipped_address = '';

$remarks         = '';
$total_quantity  = '0.000';

$items = [];

/** ---------- If EDIT: load header/items ---------- */
if ($mode === 'edit' && $id > 0) {
    $h = PurchaseOrder::GetPurchaseOrderById($id);
    if ($h) {
        $po_code         = $h->po_code;
        $po_date_display = date('d-m-Y', strtotime($h->po_date));
        $created_by_name = $h->created_by_name;
        $status          = $h->status;

        $billed_company  = $h->billed_company;
        $billed_contact  = $h->billed_contact;
        $billed_phone    = $h->billed_phone;
        $billed_email    = $h->billed_email;
        $billed_ntn      = $h->billed_ntn;
        $billed_strn     = $h->billed_strn;
        $billed_address  = $h->billed_address;

        $shipped_company = $h->shipped_company;
        $shipped_contact = $h->shipped_contact;
        $shipped_phone   = $h->shipped_phone;
        $shipped_email   = $h->shipped_email;
        $shipped_ntn     = $h->shipped_ntn;
        $shipped_strn    = $h->shipped_strn;
        $shipped_address = $h->shipped_address;

        $remarks         = $h->remarks ?? '';
        $total_quantity  = number_format((float)$h->total_quantity, 3, '.', '');

        $items = PurchaseOrderItem::GetPurchaseOrderItemsByPO($id) ?: [];
    } else {
        header("Location: purchase_order_setup.php?view&error");
        exit();
    }
}

/** ---------- POST: Save (Add/Edit) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Header
    $po_code         = trim($_POST['po_code'] ?? '');
    $po_date_display = trim($_POST['po_date'] ?? '');
    $created_by_name = trim($_POST['created_by_name'] ?? '');
    $status          = trim($_POST['status'] ?? 'draft');

    $billed_company  = trim($_POST['billed_company'] ?? '');
    $billed_contact  = trim($_POST['billed_contact'] ?? '');
    $billed_phone    = trim($_POST['billed_phone'] ?? '');
    $billed_email    = trim($_POST['billed_email'] ?? '');
    $billed_ntn      = trim($_POST['billed_ntn'] ?? '');
    $billed_strn     = trim($_POST['billed_strn'] ?? '');
    $billed_address  = trim($_POST['billed_address'] ?? '');

    $shipped_company = trim($_POST['shipped_company'] ?? '');
    $shipped_contact = trim($_POST['shipped_contact'] ?? '');
    $shipped_phone   = trim($_POST['shipped_phone'] ?? '');
    $shipped_email   = trim($_POST['shipped_email'] ?? '');
    $shipped_ntn     = trim($_POST['shipped_ntn'] ?? '');
    $shipped_strn    = trim($_POST['shipped_strn'] ?? '');
    $shipped_address = trim($_POST['shipped_address'] ?? '');

    $remarks         = trim($_POST['remarks'] ?? '');
    $total_quantity  = trim($_POST['total_quantity'] ?? '0.000');

    // Items
    $item_name = $_POST['item_name'] ?? [];
    $item_desc = $_POST['item_desc'] ?? [];
    $unit      = $_POST['unit'] ?? [];
    $quantity  = $_POST['quantity'] ?? [];

    // Validation
    $errors = [];
    if ($po_code === '' || strlen($po_code) > 30) $errors[] = "Please enter a valid PO # (max 30 chars).";
    if ($po_date_display === '')                  $errors[] = "Please select PO Date.";
    if ($created_by_name === '')                  $errors[] = "Please enter Created By.";
    if ($billed_company === '')                   $errors[] = "Please enter Billed Company.";

    $hasItem = false;
    if (is_array($item_name)) {
        foreach ($item_name as $k => $nm) {
            $q = isset($quantity[$k]) ? (float)$quantity[$k] : 0;
            if (trim($nm) !== '' && $q > 0) { $hasItem = true; break; }
        }
    }
    if (!$hasItem) $errors[] = "Please add at least one item with quantity > 0.";

    if (count($errors) === 0) {
        $po_date_sql = date('Y-m-d', strtotime(str_replace('/', '-', $po_date_display)));

        $data = [
            'po_code'         => $po_code,
            'po_date'         => $po_date_sql,
            'status'          => $status,
            'created_by_name' => $created_by_name,

            'billed_company'  => $billed_company,
            'billed_contact'  => $billed_contact ?: null,
            'billed_phone'    => $billed_phone ?: null,
            'billed_email'    => $billed_email ?: null,
            'billed_ntn'      => $billed_ntn ?: null,
            'billed_strn'     => $billed_strn ?: null,
            'billed_address'  => $billed_address ?: null,

            'shipped_company' => $shipped_company ?: null,
            'shipped_contact' => $shipped_contact ?: null,
            'shipped_phone'   => $shipped_phone ?: null,
            'shipped_email'   => $shipped_email ?: null,
            'shipped_ntn'     => $shipped_ntn ?: null,
            'shipped_strn'    => $shipped_strn ?: null,
            'shipped_address' => $shipped_address ?: null,

            'remarks'         => $remarks ?: null,
            'total_quantity'  => ($total_quantity !== '' ? $total_quantity : '0.000'),
        ];

        if ($mode === 'add') {
            $data['created_date'] = 'NOW()';
            $po_id = PurchaseOrder::AddPurchaseOrder($data);
            if ($po_id) {
                if (is_array($item_name)) {
                    foreach ($item_name as $k => $nm) {
                        $nm = trim($nm);
                        $q  = isset($quantity[$k]) ? (float)$quantity[$k] : 0;
                        if ($nm === '' || $q <= 0) continue;

                        PurchaseOrderItem::AddPurchaseOrderItem([
                            'po_id'     => $po_id,
                            'item_name' => $nm,
                            'item_desc' => isset($item_desc[$k]) ? trim($item_desc[$k]) : null,
                            'unit'      => isset($unit[$k]) ? trim($unit[$k]) : 'pcs',
                            'quantity'  => $q,
                        ]);
                    }
                }
                echo "<script>window.location.href = 'purchase_order_setup.php?view&sucess';</script>"; exit();
            } else {
                $output .= "<div id='card-alert' class='card orange lighten-5'>
                    <div class='card-content orange-text'><p>WARNING : <strong>Attention! </strong>Error while saving.</p></div>
                    <button type='button' class='close orange-text' aria-label='Close'><span aria-hidden='true'>x</span></button>
                </div>";
            }
        } else {
            $data['updated_date'] = date('Y-m-d H:i:s');
            $ok = PurchaseOrder::UpdatePurchaseOrder($id, $data);

            PurchaseOrderItem::DeleteItemsByPO($id);
            if (is_array($item_name)) {
                foreach ($item_name as $k => $nm) {
                    $nm = trim($nm);
                    $q  = isset($quantity[$k]) ? (float)$quantity[$k] : 0;
                    if ($nm === '' || $q <= 0) continue;

                    PurchaseOrderItem::AddPurchaseOrderItem([
                        'po_id'     => $id,
                        'item_name' => $nm,
                        'item_desc' => isset($item_desc[$k]) ? trim($item_desc[$k]) : null,
                        'unit'      => isset($unit[$k]) ? trim($unit[$k]) : 'pcs',
                        'quantity'  => $q,
                    ]);
                }
            }

            if ($ok !== false) {
                echo "<script>window.location.href = 'purchase_order_setup.php?view&sucess';</script>"; exit();
            } else {
                $output .= "<div id='card-alert' class='card orange lighten-5'>
                    <div class='card-content orange-text'><p>WARNING : <strong>Attention! </strong>Error while updating.</p></div>
                    <button type='button' class='close orange-text' aria-label='Close'><span aria-hidden='true'>x</span></button>
                </div>";
            }
        }
    } else {
        foreach ($errors as $val) {
            $output .= "<div id='card-alert' class='card orange lighten-5'>
                <div class='card-content orange-text'><p>WARNING : <strong>Attention! </strong>$val</p></div>
                <button type='button' class='close orange-text' aria-label='Close'><span aria-hidden='true'>x</span></button>
            </div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker_po').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: true
            });
        });
    </script>
</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><?= ($mode==='edit'?'Edit':'Create') ?> Purchase Order</h3></div>
    <hr>

    <form action="" method="post" id="po_form" novalidate="novalidate">
        <?= $output; ?>

        <div class="row">
            <div class="col m3 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" id="po_code" name="po_code" maxlength="30"
                               value='<?php echo $po_code; ?>' required/><br/>
                        <label for="po_code" class="control-label">PO # *</label>
                    </div>
                </div>
            </div>

            <div class="col m3 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" required type="text" id="datepicker_po" name="po_date"
                             value='<?php echo $po_date_display ?: ""; ?>'/><br/>
                      <label for="datepicker_po" class="control-label">PO Date *</label>

                    </div>
                </div>
            </div>

            <div class="col m3 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" id="created_by_name" name="created_by_name" maxlength="100"
                               value='<?php echo $created_by_name; ?>' required/><br/>
                        <label for="created_by_name" class="control-label">Created By *</label>
                    </div>
                </div>
            </div>

            <div class="col m3 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <select class="form-control" id="status" name="status">
                            <?php
                            $statuses = ['draft','issued','cancelled'];
                            foreach ($statuses as $st) {
                                $sel = ($status === $st) ? 'selected' : '';
                                echo "<option value=\"$st\" $sel>".ucfirst($st)."</option>";
                            }
                            ?>
                        </select>
                        <label for="status" class="control-label">Status</label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Billed From -->
        <div class="row">
            <div class="col s12"><h5>Vendor (Billed From)</h5></div>

            <div class="col m4 col s12">
  <div class="row margin">
    <div class="input-field col s12">
      <input class="form-control" type="text" name="billed_company"
             value='<?php echo ($mode === "add") ? "Daniyal Food Industries (PVT) LTD" : htmlspecialchars($billed_company); ?>'
             <?php echo ($mode === "add") ? "readonly" : ""; ?> required/><br/>
      <label class="control-label">Company *</label>
    </div>
  </div>
</div>


            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="billed_contact" readonly value='0314-6554796'/><br/>
                        <label class="control-label">Contact Person</label>
                    </div>
                </div>
            </div>

        <!--     <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="billed_phone" value='<?php echo $billed_phone; ?>'/><br/>
                        <label class="control-label">Phone</label>
                    </div>
                </div>
            </div> -->

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="email" name="billed_email" readonly value='support@daniyalfood.com'/><br/>
                        <label class="control-label">Email</label>
                    </div>
                </div>
            </div>

            <div class="col m2 col s6">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="billed_ntn" readonly value='4651512'/><br/>
                        <label class="control-label">NTN</label>
                    </div>
                </div>
            </div>

            <div class="col m2 col s6">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="billed_strn" readonly value='4651512-2'/><br/>
                        <label class="control-label">STRN</label>
                    </div>
                </div>
            </div>

        <!--    <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="billed_address" value='<?php echo $billed_address; ?>'/><br/>
                        <label class="control-label">Address</label>
                    </div>
                </div>
            </div> -->
        </div>

        <!-- Shipped From -->
        <div class="row">
            <div class="col s12"><h5>Vendor (Shipped From)</h5></div>

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_company" value='<?php echo $shipped_company; ?>'/><br/>
                        <label class="control-label">Company</label>
                    </div>
                </div>
            </div>

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_contact" value='<?php echo $shipped_contact; ?>'/><br/>
                        <label class="control-label">Contact Person</label>
                    </div>
                </div>
            </div>

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_phone" value='<?php echo $shipped_phone; ?>'/><br/>
                        <label class="control-label">Phone</label>
                    </div>
                </div>
            </div>

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="email" name="shipped_email" value='<?php echo $shipped_email; ?>'/><br/>
                        <label class="control-label">Email</label>
                    </div>
                </div>
            </div>

            <div class="col m2 col s6">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_ntn" value='<?php echo $shipped_ntn; ?>'/><br/>
                        <label class="control-label">NTN</label>
                    </div>
                </div>
            </div>

            <div class="col m2 col s6">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_strn" value='<?php echo $shipped_strn; ?>'/><br/>
                        <label class="control-label">STRN</label>
                    </div>
                </div>
            </div>

            <div class="col m4 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <input class="form-control" type="text" name="shipped_address" value='<?php echo $shipped_address; ?>'/><br/>
                        <label class="control-label">Address</label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Remarks -->
        <div class="row">
            <div class="col m12 col s12">
                <div class="row margin">
                    <div class="input-field col s12">
                        <textarea class="materialize-textarea" name="remarks" id="remarks"><?php echo $remarks; ?></textarea><br/>
                        <label for="remarks" class="control-label">Remarks</label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Items -->
        <div class="row">
            <table class="bordered responsive-table table dataTable" style="margin-top: 20px;">
                <thead>
                <tr>
                    <th>S.No</th>
                    <th>Action</th>
                    <th>Item Name</th>
                    <th>Description</th>
                    <th>Unit</th>
                    <th>Quantity</th>
                </tr>
                </thead>
                <tbody id="addNewItem">
                <?php if ($mode==='edit' && $items) {
                    $sn = 0;
                    foreach ($items as $it) { $sn++; ?>
                        <tr class="po-row">
                            <td class="sno"><?php echo $sn; ?></td>
                            <td style="width:30px;">
                                <span class="mini-stat-icon orange darken-2" style="width: 30px; height: 30px; font-size: 12px; line-height: 30px;">
                                    <i class="mdi-action-delete remove-row" style="cursor:pointer;"></i>
                                </span>
                            </td>
                            <td><input class="form-control" type="text" name="item_name[]" value="<?php echo htmlspecialchars($it->item_name); ?>" required></td>
                            <td><input class="form-control" type="text" name="item_desc[]" value="<?php echo htmlspecialchars($it->item_desc); ?>"></td>
                            <td><input class="form-control" type="text" name="unit[]" value="<?php echo htmlspecialchars($it->unit); ?>"></td>
                            <td><input class="form-control qty" type="number" step="0.001" name="quantity[]" value="<?php echo number_format((float)$it->quantity,3,'.',''); ?>"></td>
                        </tr>
                <?php } } ?>
                </tbody>
                <tbody>
                <tr>
                    <td colspan="5" style="text-align:right;">Total Quantity</td>
                    <td id="totalQty">0.000</td>
                </tr>
                </tbody>
            </table>
            <input type="hidden" name="total_quantity" id="total_quantity" value="<?php echo $total_quantity; ?>"/>
        </div>

        <div class="row">
  <div class="col m12 col s12">
    <div class="btn-group">
      <button id="newItem" type="button" class="btn waves-effect waves-light">
        Add Row
      </button>
      <button id="clearRowsBtn" type="button" class="btn red waves-effect waves-light">
        Clear
      </button>
    </div>
  </div>
</div>

        <hr/>
        <div class="row">
            <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='purchase_order_setup.php?view'">Cancel</button>
            </div>
        </div>
    </form>

</div>
</div>
</div>

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

<script>
  // Append a blank product row
  function addRow() {
  var tr =
    '<tr class="po-row">' +
      '<td class="sno"></td>' +
      '<td style="width:30px;">' +
        '<span class="mini-stat-icon orange darken-2" style="width:30px;height:30px;font-size:12px;line-height:30px;">' +
          '<i class="mdi-action-delete remove-row" style="cursor:pointer;"></i>' +
        '</span>' +
      '</td>' +
      '<td><input class="form-control" type="text" name="item_name[]" required></td>' +
      '<td><input class="form-control" type="text" name="item_desc[]"></td>' +

      // ✅ Unit dropdown instead of text input
      '<td>' +
        '<select class="browser-default" name="unit[]" required>' +
          '<option value="Pcs">Pcs</option>' +
          '<option value="Kg">Kg</option>' +
          '<option value="Bag">Bag</option>' +
        '</select>' +
      '</td>' +

      '<td><input class="form-control qty" type="number" step="0.001" name="quantity[]" value="0.000"></td>' +
    '</tr>';

  $("#addNewItem").append(tr);
  numbering();
  Calculate();
}
  
  

  // Re-number S.No
  function numbering() {
    var count = 0;
    $('#addNewItem tr.po-row td.sno').each(function () {
      count++;
      $(this).text(count);
    });
  }

  // Recalculate total quantity
  function Calculate() {
    var tqty = 0.0;
    $("input[name='quantity[]']").each(function () {
      var q = parseFloat($(this).val());
      if (!isNaN(q)) tqty += q;
    });
    $('#totalQty').text(tqty.toFixed(3));
    $('#total_quantity').val(tqty.toFixed(3));
  }

  // Wire up events
  $(document).ready(function () {
    // Add row (support both ids: newItem and addRowBtn)
    $(document).on('click', '#newItem, #addRowBtn', function () {
      addRow();
    });

  // ✅ Clear only the last row when Clear button is pressed
$('#clearRowsBtn').on('click', function () {
  var rows = $('#addNewItem tr.po-row');
  if (rows.length > 1) {
    // Remove only the last row
    rows.last().remove();
  } else {
    // If only one row exists, just clear its inputs instead of deleting it
    var row = rows.last();
    row.find("input[type='text'], input[type='number'], textarea").val('');
    row.find("select").prop('selectedIndex', 0);
    if (window.M && M.FormSelect) {
      M.FormSelect.init(document.querySelectorAll('select'));
    }
  }
  numbering();
  Calculate();
});


    // Remove a row
    $(document).on('click', '.remove-row', function () {
      $(this).closest('tr').remove();
      numbering();
      Calculate();
      // If nothing left, keep one blank row
      if ($('#addNewItem tr').length === 0) addRow();
    });

    // Recalc on qty input
    $(document).on('input', "input[name='quantity[]']", function () {
      Calculate();
    });

    // Show 1st row on load (only if none exist — so edit mode with rows won’t duplicate)
    if ($('#addNewItem tr').length === 0) {
      addRow();
    } else {
      numbering();
      Calculate();
    }
  });
  
  function dmyToSql(dmy){
  if(!dmy) return '';
  var p = dmy.split('-');
  if(p.length!==3) return '';
  return p[2]+'-'+p[1]+'-'+p[0];
}

function refreshPoCode(){
  var dmy = $('#datepicker_po').val();
  var sql = dmyToSql(dmy);
  if(!sql) return;

  $.get('ajax_get_next_po_code.php', { date: sql }, function(resp){
    if(resp && resp.ok && resp.code){
      $('#po_code').val(resp.code);
      if(window.M && M.updateTextFields){ M.updateTextFields(); }
    }
  }, 'json');
}

$(function(){
  // ensure datepicker present (Materialize)
  $('#datepicker_po').pickadate({
    format: 'dd-mm-yyyy',
    selectMonths: true,
    selectYears: true
  });

  // --- ADD MODE: set today if empty, then generate once on load
  <?php if ($mode === 'add'): ?>
    if(!$('#datepicker_po').val()){
      $('#datepicker_po').val('<?php echo date('d-m-Y'); ?>');
      if(window.M && M.updateTextFields){ M.updateTextFields(); }
    }
    refreshPoCode();
  <?php endif; ?>

  // --- ALL MODES (add + edit): regenerate when date changes
  $('#datepicker_po').on('change', refreshPoCode);

  // also hook pickadate 'set' event
  var picker = $('#datepicker_po').pickadate('picker');
  if(picker){
    picker.on('set', function(e){
      if(e.select){ setTimeout(refreshPoCode, 0); }
    });
  }
});
</script>

</body>
</html>
