<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>

<?php
// This view supports BOTH Create and Edit.
// Controller should pass:
// - Create: $staff_id, $staff_name
// - Edit:   $decl, $items, $files, $is_edit=true
$is_edit = isset($is_edit) && $is_edit;

$actionUrl = $is_edit
    ? admin_url('staff_declaration/update/' . (int)$decl['id'])
    : admin_url('staff_declaration/store');

// Header values
$staffName   = $is_edit ? ($decl['staff_name'] ?? '') : ($staff_name ?? '');
$staffCode   = $is_edit ? ($decl['staff_code'] ?? '') : '';
$position    = $is_edit ? ($decl['position'] ?? '') : '';
$department  = $is_edit ? ($decl['department'] ?? '') : '';
$signature   = $is_edit ? ($decl['employee_signature'] ?? $staffName) : $staffName;
$empDate     = $is_edit ? ($decl['employee_date'] ?? date('Y-m-d')) : date('Y-m-d');

// Gift rows
$existingItems = $is_edit ? ($items ?? []) : [];
$initialRowCount = max(3, count($existingItems));
?>
<?php $year = (int)($decl['year'] ?? date('Y')); ?>
<?php $open = hc_submission_is_open($year); ?>
<style>
  :root{
    --inceif-primary:#0f4a56;
    --inceif-border:#e5e7eb;
    --inceif-muted:#6b7280;
    --inceif-bg:#f8fafc;
  }

  /* Wrapper (optional) */
  .coi-wrap{
    
    margin: 0 auto;
  }

  /* Card */
  .coi-card{
    background:#fff;
  
    border-radius:12px;
    padding:18px 20px;
    margin: 14px 0;
  
  }

  .coi-card__header{
    display:flex;
    align-items:center;
    gap:10px;
    margin-bottom:10px;
  }

  .coi-card__icon{
    width:36px;
    height:36px;
    border-radius:10px;
    background: rgba(15,74,86,.08);
    display:flex;
    align-items:center;
    justify-content:center;
    color: var(--inceif-primary);
    font-size:16px;
    flex: 0 0 36px;
  }

  .coi-card__title{
    font-size:16px;
    font-weight:700;
    color:#111827;
    margin:0;
    line-height:1.25;
  }

  .coi-card p{
    margin: 0 0 10px;
    color:#111827;
    font-size:14px;
    line-height:1.75;
    text-align: justify;
  }

  .coi-card .coi-muted{
    color: var(--inceif-muted);
  }

  /* Lists */
  .coi-card ol{
    margin: 8px 0 0;
    padding-left: 18px;
    color:#111827;
    font-size:14px;
    line-height:1.75;
  }
  .coi-card ol li{ margin: 6px 0; }

  /* Highlight callout inside card */
  .coi-callout{
    background: var(--inceif-bg);
    border:1px solid var(--inceif-border);
    border-left: 4px solid var(--inceif-primary);
    padding: 12px 14px;
    border-radius:10px;
    margin-top: 12px;
  }
  .coi-callout strong{ color:#111827; }

  /* Checkbox section */
  .coi-confirm{
    margin-top: 14px;
    padding-top: 12px;
    border-top: 1px dashed var(--inceif-border);
  }
  .coi-confirm .checkbox{
    margin: 0;
  }
  .coi-confirm label{
    font-size:14px;
    line-height:1.65;
    color:#111827;
  }

  /* Small screens */
  @media (max-width: 576px){
    .coi-card{ padding:14px 14px; border-radius:10px; }
    .coi-card__title{ font-size:15px; }
    .coi-card p, .coi-card ol{ font-size:13.5px; }
  }
   /* Force list to show 1.Item (no space after dot) */
  .coi-list-tight{
    list-style: none;            /* hide default 1. */
    counter-reset: coi;
    padding-left: 0;
    margin: 8px 0 0;
  }

  .coi-list-tight > li{
    counter-increment: coi;
    position: relative;
    padding-left: 0;             /* no indent */
    margin: 6px 0;
  }

  .coi-list-tight > li::before{
    content: counter(coi) ".";   /* "1." */
    font-weight: 700;
    margin-right: 0;             /* NO SPACE after dot */
  }
</style>
<div id="wrapper">
  <div class="content">
    <div class="row">
      <div class="col-md-12">
        <div class="panel_s">
          <div class="panel-body">
              <?php if (!$open) { ?>
  <div class="alert alert-warning">
    Submission is closed after 31 January.
  </div>
<?php } ?>
            <div class="clearfix">
              <h4 class="pull-left tw-font-bold">
                <?php echo $is_edit ? ('Edit Declaration #' . (int)$decl['id']) : _l('staff_declaration'); ?>
              </h4>

              <?php if ($is_edit) { ?>
                <div class="pull-right">
                  <a class="btn btn-default" href="<?php echo admin_url('staff_declaration/view/' . (int)$decl['id']); ?>">
                    <i class="fa fa-eye"></i> View
                  </a>
                </div>
              <?php } ?>
            </div>

            <p class="text-muted mbot15"></p>
            <div class="coi-card">
    <div class="coi-card__header">
      <div class="coi-card__icon"><i class="fa fa-info-circle"></i></div>
      <h4 class="coi-card__title">Use this form to report business-related benefits as they occur.</h4>
    </div>
    <p class="coi-muted">
     <ol class="coi-list-tight">
         <li> Disclosure is mandatory for items >RM200 or any benefit perceived as lavish/influential.</li>
         <li> Declarations should be made within 7 days of receipt or offer.</li>
         <li> This submission fulfils your ongoing duty to disclose outside of the annual review cycle.</li>
     </ol>
    </p>
  </div>
            <hr class="hr-panel-heading" />

            <?php echo form_open_multipart($actionUrl, ['id' => 'giftForm']); ?>

            <h5><strong>Part A — Employee Information</strong></h5>
            <div class="row">
              <div class="col-md-6">
                <label>Name</label>
                <input type="text" class="form-control" name="name_display"
                       value="<?php echo htmlspecialchars($staffName); ?>" readonly>
              </div>

              <div class="col-md-6">
                <label>Staff ID <span class="text-danger">*</span></label>
                <input type="text" class="form-control" name="staff_code" placeholder="e.g. 000244"
                       value="<?php echo e($is_edit ? ($decl['staff_code'] ?? '') : ($staff_code ?? '')); ?>" readonly>
              </div>

              <div class="col-md-6 mtop10">
                <label>Position <span class="text-danger">*</span></label>
                <input type="text" class="form-control" name="position"
                       value="<?php echo e($is_edit ? ($decl['position'] ?? '') : ($staff_position ?? '')); ?>" readonly>
              </div>

              <div class="col-md-6 mtop10">
                <label>Department</label>
                    <input type="text" class="form-control" name="department" required
                  value="<?php echo e($department_display ?: 'Department Not assigned'); ?>" readonly>
                  

<?php if (!empty($department_id)) { ?>
  <input type="hidden" name="department_id" value="<?php echo (int)$department_id; ?>">
<?php } ?>
              </div>
            </div>

            <hr>
            <h5><strong>Part B — Gift / Hospitality / Entertainment Details</strong></h5>

            <div class="table-responsive">
  <table class="table table-bordered" id="giftTable">
    <thead>
      <tr>
        <th style="width:50px">No.</th>
        <th style="min-width:140px">Date Received</th>

        <!-- ✅ NEW -->
        <th style="min-width:220px">Item Category</th>

        <th>Description</th>
        <th style="width:130px">Estimated Value (RM)</th>
        <th>Provider / Donor</th>
        <th>Business Relationship</th>
        <th>Purpose/Occasion</th>
        <th>Remarks</th>
      </tr>
    </thead>

    <tbody id="giftRows">
      <?php for ($i = 0; $i < $initialRowCount; $i++) {
          $it = $existingItems[$i] ?? [];
          $cat = $it['category'] ?? '';
      ?>
        <tr>
          <td><?php echo $i + 1; ?></td>

          <td>
            <input type="date" class="form-control"
                   name="items[<?php echo $i; ?>][date_received]"
                   value="<?php echo htmlspecialchars($it['date_received'] ?? ''); ?>">
          </td>

          <!-- ✅ NEW CATEGORY DROPDOWN -->
          <td>
            <select class="form-control"
                    name="items[<?php echo $i; ?>][category]">
              <option value="">-- Select --</option>
              <option value="Physical Gift" <?php echo ($cat==='Physical Gift'?'selected':''); ?>>Physical Gift</option>
              <option value="Business Meal" <?php echo ($cat==='Business Meal'?'selected':''); ?>>Business Meal</option>
              <option value="Event Invitation (Hospitality)" <?php echo ($cat==='Event Invitation (Hospitality)'?'selected':''); ?>>
                Event Invitation (Hospitality)
              </option>
              <option value="Travel/Accommodation" <?php echo ($cat==='Travel/Accommodation'?'selected':''); ?>>
                Travel/Accommodation
              </option>
            </select>
          </td>

          <td>
            <input type="text" class="form-control"
                   placeholder="e.g., Hamper"
                   name="items[<?php echo $i; ?>][description]"
                   value="<?php echo htmlspecialchars($it['description'] ?? ''); ?>">
          </td>

          <td>
            <input type="number" step="0.01" min="0" class="form-control"
                   name="items[<?php echo $i; ?>][estimated_value]"
                   value="<?php echo htmlspecialchars($it['estimated_value'] ?? ''); ?>">
          </td>

          <td>
            <input type="text" class="form-control"
                   name="items[<?php echo $i; ?>][gift_from]"
                   value="<?php echo htmlspecialchars($it['gift_from'] ?? ''); ?>">
          </td>

          <td>
            <input type="text" class="form-control"
                   name="items[<?php echo $i; ?>][relationship]"
                   value="<?php echo htmlspecialchars($it['relationship'] ?? ''); ?>">
          </td>

          <td>
            <input type="text" class="form-control"
                   name="items[<?php echo $i; ?>][purpose]"
                   value="<?php echo htmlspecialchars($it['purpose'] ?? ''); ?>">
          </td>

          <td>
            <input type="text" class="form-control"
                   name="items[<?php echo $i; ?>][action_taken]"
                   value="<?php echo htmlspecialchars($it['action_taken'] ?? ''); ?>">
          </td>
        </tr>
      <?php } ?>
    </tbody>
  </table>
</div>


            <div class="clearfix">
              <button type="button" class="btn btn-info" id="addRow">
                <i class="fa fa-plus"></i> Add row
              </button>
              <button type="button" class="btn btn-default" id="removeRow">
                <i class="fa fa-minus"></i> Remove last row
              </button>

              <div class="pull-right">
                <label class="mright10">Attachments</label>
                <input type="file" name="attachments[]" multiple>
              </div>
            </div>

            <?php if ($is_edit && !empty($files)) { ?>
              <div class="mtop15">
                <h5 class="no-margin"><strong>Existing Attachments</strong></h5>
                <p class="text-muted">You can download or delete existing files. You can also upload new files above.</p>

                <div class="table-responsive">
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th>File</th>
                        <th style="width:160px">Uploaded</th>
                        <th style="width:180px">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($files as $f) { ?>
                        <tr>
                          <td>
                            <a href="<?php echo admin_url('staff_declaration/download_file/' . (int)$decl['id'] . '/' . (int)$f['id']); ?>">
                              <?php echo htmlspecialchars($f['original_name'] ?: $f['file_name']); ?>
                            </a>
                          </td>
                          <td><?php echo !empty($f['dateadded']) ? _dt($f['dateadded']) : '-'; ?></td>
                          <td>
                            <a class="btn btn-xs btn-default"
                               href="<?php echo admin_url('staff_declaration/download_file/' . (int)$decl['id'] . '/' . (int)$f['id']); ?>">
                              <i class="fa fa-download"></i> Download
                            </a>

                            <a class="btn btn-xs btn-danger _delete"
                               href="<?php echo admin_url('staff_declaration/delete_file/' . (int)$decl['id'] . '/' . (int)$f['id']); ?>">
                              <i class="fa fa-trash"></i> Delete
                            </a>
                          </td>
                        </tr>
                      <?php } ?>
                    </tbody>
                  </table>
                </div>
              </div>
            <?php } ?>

            <hr>
            <style>
  .declaration-box{
    background:#fff;
    border:1px solid #e5e7eb;
    border-left:5px solid #0ea5a4;
    border-radius:10px;
    padding:16px 18px;
    box-shadow:0 1px 2px rgba(0,0,0,.04);
    margin-top:15px;
  }

  .declaration-title{
    display:flex;
    align-items:center;
    gap:10px;
    font-weight:700;
    font-size:15px;
    color:#0f172a;
    margin-bottom:10px;
  }

  .declaration-title i{
    width:28px;
    height:28px;
    border-radius:8px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    background:rgba(14,165,164,.12);
    color:#0ea5a4;
    font-size:14px;
  }

  .declaration-lead{
    margin:0 0 10px;
    color:#334155;
    line-height:1.65;
  }

  .declaration-list{
    margin:0;
    padding-left:18px;
    color:#475569;
    line-height:1.7;
  }

  .declaration-list li{
    margin:8px 0;
    padding-left:6px;
  }

  /* Optional: nicer numbering */
  .declaration-list{
    list-style:none;
    counter-reset: dec;
    padding-left:0;
  }
  .declaration-list li{
    counter-increment: dec;
    position:relative;
    padding-left:34px;
  }
  .declaration-list li::before{
    content: counter(dec) ".";
    position:absolute;
    left:0;
    top:0;
    font-weight:700;
    color:#0f172a;
    width:26px;
    text-align:right;
  }
</style>

           
          <div class="declaration-box">
  <div class="declaration-title">
    <i class="fa fa-shield"></i> Declaration and Request for Approval
  </div>

  <p class="declaration-lead">
    I, the undersigned, hereby declare and acknowledge that:
  </p>

  <ol class="declaration-list">
    <li>The information provided regarding these gifts / hospitality / entertainment is true, accurate, and complete.</li>
    <li>I have read and understood the Gifts and Entertainment clauses within the INCEIF Conflict of Interest Policy and i am seeking formal approval to retain or accept the Gift / Hospitality / Entertainment described above.</li>
    <li>I understand that failure to disclose or providing false information is a breach of the University’s Integrity standards and may lead to disciplinary action.</li>
  </ol>
</div><br>


            <div class="row">
              <div class="col-md-6">
                <label>Employee Signature</label>
                <input type="text" class="form-control" name="employee_signature" required
                       value="<?php echo htmlspecialchars($signature); ?>">
              </div>
              <div class="col-md-6">
                <label>Date</label>
                <input type="date" class="form-control" name="employee_date" required
                       value="<?php echo htmlspecialchars($empDate); ?>">
              </div>
            </div>

            <div class="mtop20 text-right">
              <button type="submit" class="btn btn-primary" <?php echo $open ? '' : 'disabled'; ?>>
                <?php echo $is_edit ? '<i class="fa fa-save"></i> Update' : '<i class="fa fa-check"></i> Submit'; ?>
              </button>

              <button type="button" class="btn btn-default" onclick="window.print()">
                <i class="fa fa-print"></i> Print
              </button>

              <a class="btn btn-default" href="<?php echo admin_url('staff_declaration'); ?>">
                <i class="fa fa-arrow-left"></i> <?php echo _l('back'); ?>
              </a>
            </div>

            <?php echo form_close(); ?>

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

<?php init_tail(); ?>

 <script>

(function () {
  const tbody = document.getElementById('giftRows');
  const addBtn = document.getElementById('addRow');
  const removeBtn = document.getElementById('removeRow');

  // Choose which fields become required when row has data:
  // (set to true for ALL inputs, or list only certain keys)
   const REQUIRED_KEYS = [
    'date_received',
    'category',
    'description',
    'estimated_value',
    'gift_from',
    'relationship',
    'purpose',
    'action_taken'
  ]
 function rowTemplate(idx){
    const i = idx - 1;
    return `
      <tr>
        <td>${idx}</td>
        <td><input type="date" class="form-control" name="items[${i}][date_received]"></td>

        <td>
          <select class="form-control" name="items[${i}][category]">
            <option value="">-- Select --</option>
            <option value="Physical Gift">Physical Gift</option>
            <option value="Business Meal">Business Meal</option>
            <option value="Event Invitation (Hospitality)">Event Invitation (Hospitality)</option>
            <option value="Travel/Accommodation">Travel/Accommodation</option>
          </select>
        </td>

        <td><input type="text" class="form-control" placeholder="e.g., Hamper" name="items[${i}][description]"></td>
        <td><input type="number" step="0.01" min="0" class="form-control" name="items[${i}][estimated_value]"></td>
        <td><input type="text" class="form-control" name="items[${i}][gift_from]"></td>
        <td><input type="text" class="form-control" name="items[${i}][relationship]"></td>
        <td><input type="text" class="form-control" name="items[${i}][purpose]"></td>
        <td><input type="text" class="form-control" name="items[${i}][action_taken]"></td>
      </tr>`;
  }

  function getInputs(row){
    return Array.from(row.querySelectorAll('input, select, textarea'));
  }

  function hasAnyValue(row){
    return getInputs(row).some(el => String(el.value || '').trim() !== '');
  }

  function shouldRequire(el){
    // Extract key from name: items[0][date_received] -> date_received
    const m = (el.name || '').match(/\[([^\]]+)\]$/);
    const key = m ? m[1] : '';
    return REQUIRED_KEYS.includes(key);
  }

  function setRowRequired(row, required){
    getInputs(row).forEach(el => {
      if (!el.name) return;
      if (!shouldRequire(el)) return;         // only require selected fields
      el.required = required;

      // Optional: for number fields, avoid "required" firing on empty with min=0 weirdness
      // (not necessary usually, but safe)
      if (!required && el.type === 'number') {
        el.setCustomValidity('');
      }
    });
  }

  function evaluateRow(row){
    const any = hasAnyValue(row);
    setRowRequired(row, any);
  }

  function evaluateAllRows(){
    Array.from(tbody.rows).forEach(evaluateRow);
  }

  function addRow(){
    const idx = tbody.rows.length + 1;
    tbody.insertAdjacentHTML('beforeend', rowTemplate(idx));
    const newRow = tbody.rows[tbody.rows.length - 1];
    evaluateRow(newRow); // start not-required (empty row)
  }

  function renumberRows(){
    for (let r = 0; r < tbody.rows.length; r++){
      tbody.rows[r].cells[0].textContent = (r + 1);
    }
  }

  // Live: whenever user types in any row, toggle required for that row
  tbody.addEventListener('input', function (e) {
    const row = e.target.closest('tr');
    if (row) evaluateRow(row);
  });
  tbody.addEventListener('change', function (e) {
    const row = e.target.closest('tr');
    if (row) evaluateRow(row);
  });

  addBtn.addEventListener('click', addRow);

  removeBtn.addEventListener('click', function () {
    const n = tbody.rows.length;
    if (n > 1) {
      tbody.deleteRow(n - 1);
      renumberRows();
      evaluateAllRows();
    }
  });

  // IMPORTANT: run once on page load so prefilled rows become required automatically
  evaluateAllRows();

  // If you want extra safety, also enforce on submit:
  const form = tbody.closest('form');
  if (form) {
    form.addEventListener('submit', function () {
      evaluateAllRows();
    });
  }
})();


// (function () {
//   const tbody = document.getElementById('giftRows');
//   const addBtn = document.getElementById('addRow');
//   const removeBtn = document.getElementById('removeRow');

//   function rowTemplate(idx){
//     const i = idx - 1; // form index
//     return `
//       <tr>
//         <td>${idx}</td>
//         <td><input type="date" class="form-control" name="items[${i}][date_received]"></td>
//         <td><input type="text" class="form-control" name="items[${i}][description]"></td>
//         <td><input type="number" step="0.01" min="0" class="form-control" name="items[${i}][estimated_value]"></td>
//         <td><input type="text" class="form-control" name="items[${i}][gift_from]"></td>
//         <td><input type="text" class="form-control" name="items[${i}][relationship]"></td>
//         <td><input type="text" class="form-control" name="items[${i}][purpose]"></td>
//         <td><input type="text" class="form-control" name="items[${i}][action_taken]"></td>
//       </tr>`;
//   }

//   function addRow(){
//     const idx = tbody.rows.length + 1;
//     tbody.insertAdjacentHTML('beforeend', rowTemplate(idx));
//   }

//   function renumberRows(){
//     for (let r = 0; r < tbody.rows.length; r++){
//       tbody.rows[r].cells[0].textContent = (r + 1);
//     }
//   }

//   addBtn.addEventListener('click', addRow);

//   removeBtn.addEventListener('click', function () {
//     const n = tbody.rows.length;
//     if (n > 1) {
//       tbody.deleteRow(n - 1);
//       renumberRows();
//     }
//   });

// })();
 </script>
