<?php
// ============================================================
// modules/configuration/departments.php – Config CRUD template
// (Same pattern used for all config modules)
// ============================================================
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();

// ── Router: determine which config module ──────────────────
$module   = get('m') ?: 'departments';
$configs  = [
    'departments'  => ['table'=>'departments',   'label'=>'Department',   'page'=>'Departments',   'cols'=>['name','code']],
    'locations'    => ['table'=>'locations',     'label'=>'Location',     'page'=>'Locations',     'cols'=>['name','code','city','state','address']],
    'branches'     => ['table'=>'branches',      'label'=>'Branch',       'page'=>'Branches',      'cols'=>['name','code']],
    'grades'       => ['table'=>'grades',        'label'=>'Grade',        'page'=>'Grades',        'cols'=>['name','code','description']],
    'categories'   => ['table'=>'categories',    'label'=>'Category',     'page'=>'Categories',    'cols'=>['name','code']],
    'designations' => ['table'=>'designations',  'label'=>'Designation',  'page'=>'Designations',  'cols'=>['name','code']],
    'shifts'       => ['table'=>'shifts',        'label'=>'Shift',        'page'=>'Shifts',        'cols'=>['name','code','start_time','end_time','grace_in_minutes','work_hours']],
    'leave_types'  => ['table'=>'leave_types',   'label'=>'Leave Type',   'page'=>'Leave Types',   'cols'=>['name','code','days_per_year']],
    'banks'        => ['table'=>'banks',         'label'=>'Bank',         'page'=>'Bank Master',   'cols'=>['name','code','ifsc_prefix']],
    'doc_types'    => ['table'=>'document_types','label'=>'Document Type','page'=>'Document Types','cols'=>['name','code']],
    'skills'       => ['table'=>'skills_master', 'label'=>'Skill',        'page'=>'Skills Master', 'cols'=>['name','category']],
    'reasons'      => ['table'=>'leaving_reasons','label'=>'Leaving Reason','page'=>'Leaving Reasons','cols'=>['reason']],
    'advance_heads'=> ['table'=>'advance_heads', 'label'=>'Advance Head', 'page'=>'Advance Heads', 'cols'=>['name','code','max_amount','max_installments','interest_rate']],
];

if (!isset($configs[$module])) { $module = 'departments'; }
$cfg   = $configs[$module];
$table = $cfg['table'];
$label = $cfg['label'];
$page  = $cfg['page'];
$cols  = $cfg['cols'];

// POST handlers
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');

    if ($action === 'save') {
        $data = [];
        foreach ($cols as $col) {
            $data[$col] = post($col);
        }
        $data['is_active'] = isset($_POST['is_active']) ? 1 : 0;

        // Locations: save latitude, longitude, radius
        if ($module === 'locations') {
            $lat = post('latitude');
            $lng = post('longitude');
            $radius = postInt('geofence_radius') ?: 25;
            if ($lat !== '' && $lng !== '') {
                $data['latitude']          = (float)$lat;
                $data['longitude']         = (float)$lng;
                $data['geofence_radius']   = $radius;
            }
        }

        $id = postInt('id');
        if ($id) {
            $db->updateRow($table, $data, $id);
            auditLog('UPDATE', $table, $id, [], $data);
            setFlash('success', "$label updated successfully.");
        } else {
            $newId = $db->insertRow($table, $data);
            auditLog('INSERT', $table, $newId, [], $data);
            setFlash('success', "$label added successfully.");
        }
    }

    if ($action === 'toggle') {
        $id     = postInt('id');
        $active = postInt('active');
        $db->execute("UPDATE `$table` SET is_active=? WHERE id=?", [$active, $id]);
        jsonResponse(true, $active ? "$label activated" : "$label deactivated");
    }

    if ($action === 'delete') {
        $id = postInt('id');
        // Soft delete
        $db->execute("UPDATE `$table` SET is_active=0 WHERE id=?", [$id]);
        setFlash('success', "$label deleted.");
    }

    header("Location: departments.php?m=$module"); exit;
}

// Fetch records
$records = $db->fetchAll("SELECT * FROM `$table` ORDER BY id DESC");

// Edit record
$editId  = cleanInt($_GET['edit'] ?? 0);
$editRec = $editId ? $db->fetchOne("SELECT * FROM `$table` WHERE id=?", [$editId]) : null;

$headerActions = '<a href="departments.php?m='.$module.'&edit=0" class="btn btn-pc btn-sm">
  <i class="ti ti-plus me-1"></i>Add '.$label.'</a>';
include __DIR__ . '/../../includes/header.php';
?>

<!-- Sub-navigation -->
<div class="d-flex gap-1 flex-wrap mb-3">
  <?php foreach ($configs as $key => $c): ?>
  <a href="?m=<?= $key ?>" class="btn btn-sm <?= $key===$module?'btn-pc':'btn-outline-secondary' ?>">
    <?= $c['page'] ?>
  </a>
  <?php endforeach; ?>
</div>

<div class="row g-3">
  <!-- Form -->
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><?= $editRec ? "Edit $label" : "Add $label" ?></div>
      <form method="POST" action="departments.php?m=<?= $module ?>">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="save">
        <?php if ($editRec): ?><input type="hidden" name="id" value="<?= $editRec['id'] ?>"><?php endif; ?>

        <?php foreach ($cols as $col):
          $type = in_array($col,['start_time','end_time']) ? 'time' : (in_array($col,['max_amount','interest_rate','grace_in_minutes','days_per_year','work_hours','max_installments']) ? 'number' : 'text');
          $label2 = ucwords(str_replace('_',' ',$col));
          $val    = $editRec[$col] ?? '';
        ?>
        <div class="mb-2">
          <label class="pc-label"><?= $label2 ?></label>
          <input type="<?= $type ?>" name="<?= $col ?>" class="form-control form-control-sm"
            value="<?= clean($val) ?>"
            <?= in_array($col,['name','code']) ? 'required' : '' ?>
            <?= $type==='number' ? 'step="0.01"' : '' ?>>
        </div>
        <?php endforeach; ?>

        <!-- Special fields for specific modules -->
        <?php if ($module === 'leave_types'): ?>
        <div class="row g-2 mb-2">
          <div class="col-6"><label class="pc-label">Carry Forward</label>
            <select name="carry_forward" class="form-select form-select-sm">
              <option value="0" <?= ($editRec['carry_forward']??0)==0?'selected':'' ?>>No</option>
              <option value="1" <?= ($editRec['carry_forward']??0)==1?'selected':'' ?>>Yes</option>
            </select></div>
          <div class="col-6"><label class="pc-label">Encashable</label>
            <select name="encashable" class="form-select form-select-sm">
              <option value="0" <?= ($editRec['encashable']??0)==0?'selected':'' ?>>No</option>
              <option value="1" <?= ($editRec['encashable']??0)==1?'selected':'' ?>>Yes</option>
            </select></div>
          <div class="col-6"><label class="pc-label">Is Paid</label>
            <select name="is_paid" class="form-select form-select-sm">
              <option value="1" <?= ($editRec['is_paid']??1)==1?'selected':'' ?>>Yes</option>
              <option value="0" <?= ($editRec['is_paid']??1)==0?'selected':'' ?>>No</option>
            </select></div>
          <div class="col-6"><label class="pc-label">Half Day</label>
            <select name="half_day_allowed" class="form-select form-select-sm">
              <option value="1" <?= ($editRec['half_day_allowed']??1)==1?'selected':'' ?>>Yes</option>
              <option value="0" <?= ($editRec['half_day_allowed']??1)==0?'selected':'' ?>>No</option>
            </select></div>
        </div>
        <?php endif; ?>

        <?php if ($module === 'advance_heads'): ?>
        <div class="mb-2"><label class="pc-label">Interest Type</label>
          <select name="interest_type" class="form-select form-select-sm">
            <option value="simple" <?= ($editRec['interest_type']??'simple')==='simple'?'selected':'' ?>>Simple</option>
            <option value="compound" <?= ($editRec['interest_type']??'')==='compound'?'selected':'' ?>>Compound</option>
          </select></div>
        <?php endif; ?>

        <?php if ($module === 'locations'): ?>
        <hr class="my-2">
        <div class="mb-1">
          <label class="pc-label fw-semibold text-primary">
            <i class="ti ti-map-pin me-1"></i>Geofencing (Mobile Check-In/Out)
          </label>
        </div>
        <div class="mb-2">
          <label class="pc-label">Latitude</label>
          <input type="number" step="0.00000001" name="latitude" id="inp_lat"
            class="form-control form-control-sm"
            value="<?= $editRec['latitude'] ?? '' ?>"
            placeholder="e.g. 13.0827">
        </div>
        <div class="mb-2">
          <label class="pc-label">Longitude</label>
          <input type="number" step="0.00000001" name="longitude" id="inp_lng"
            class="form-control form-control-sm"
            value="<?= $editRec['longitude'] ?? '' ?>"
            placeholder="e.g. 80.2707">
        </div>
        <div class="mb-2">
          <label class="pc-label">Geofence Radius (meters)</label>
          <input type="number" name="geofence_radius" id="inp_radius"
            class="form-control form-control-sm"
            value="<?= $editRec['geofence_radius'] ?? 25 ?>"
            min="10" max="500" placeholder="25">
          <small class="text-muted">Default: 25m — employees must be within this radius to check-in/out</small>
        </div>

        <!-- Map Picker -->
        <div class="mb-2">
          <button type="button" class="btn btn-sm btn-outline-primary w-100" onclick="openMapPicker()">
            <i class="ti ti-map me-1"></i>
            <?= ($editRec['latitude'] ?? '') ? 'Update from Map' : 'Pick from Map' ?>
          </button>
        </div>

        <?php if ($editRec['latitude'] ?? ''): ?>
        <div class="mb-2 p-2 bg-success bg-opacity-10 rounded border border-success">
          <small class="text-success">
            <i class="ti ti-check me-1"></i>
            Geofencing set: <?= round($editRec['latitude'],6) ?>, <?= round($editRec['longitude'],6) ?>
            | Radius: <?= $editRec['geofence_radius'] ?? 25 ?>m
          </small>
        </div>
        <?php else: ?>
        <div class="mb-2 p-2 bg-warning bg-opacity-10 rounded border border-warning">
          <small class="text-warning">
            <i class="ti ti-alert-triangle me-1"></i>
            No location set — Mobile check-in/out will not work for this location
          </small>
        </div>
        <?php endif; ?>
        <?php endif; ?>

        <div class="form-check mb-3">
          <input class="form-check-input" type="checkbox" name="is_active" id="isActive" value="1"
            <?= ($editRec['is_active']??1) ? 'checked' : '' ?>>
          <label class="form-check-label small" for="isActive">Active</label>
        </div>

        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-pc btn-sm">
            <?= $editRec ? 'Update' : 'Add' ?> <?= $label ?>
          </button>
          <?php if ($editRec): ?>
          <a href="?m=<?= $module ?>" class="btn btn-sm btn-outline-secondary">Cancel</a>
          <?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <!-- Records Table -->
  <div class="col-md-8">
    <div class="pc-card">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="fw-semibold"><?= $page ?> <span class="badge bg-secondary ms-1"><?= count($records) ?></span></div>
        <a href="?m=<?= $module ?>&format=csv" class="btn btn-sm btn-outline-secondary">
          <i class="ti ti-download me-1"></i>Export
        </a>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead>
            <tr>
              <th>#</th>
              <?php foreach ($cols as $col): ?>
              <th><?= ucwords(str_replace('_',' ',$col)) ?></th>
              <?php endforeach; ?>
              <th>Status</th><th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($records as $i => $rec): ?>
          <tr class="<?= !$rec['is_active']?'table-secondary opacity-50':'' ?>">
            <td class="text-muted"><?= $i+1 ?></td>
            <?php foreach ($cols as $col): ?>
            <td><?= clean($rec[$col]??'') ?></td>
            <?php endforeach; ?>
            <td>
              <div class="form-check form-switch mb-0">
                <input class="form-check-input" type="checkbox" <?= $rec['is_active']?'checked':'' ?>
                  onchange="toggleRecord(<?= $rec['id'] ?>, this.checked?1:0, '<?= $module ?>')">
              </div>
            </td>
            <td>
              <a href="?m=<?= $module ?>&edit=<?= $rec['id'] ?>" class="btn btn-sm btn-outline-primary" title="Edit">
                <i class="ti ti-edit"></i>
              </a>
              <button class="btn btn-sm btn-outline-danger" title="Delete"
                onclick="deleteRecord(<?= $rec['id'] ?>, '<?= addslashes($rec['name']??$rec[$cols[0]]) ?>', '<?= $module ?>')">
                <i class="ti ti-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$records): ?>
          <tr><td colspan="<?= count($cols)+3 ?>" class="text-center py-4 text-muted">No records found</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Confirm Delete</h6></div>
      <div class="modal-body" id="deleteMsg">Are you sure?</div>
      <div class="modal-footer">
        <button class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <form method="POST" class="d-inline" id="deleteForm">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" id="deleteId">
          <button type="submit" class="btn btn-sm btn-danger">Delete</button>
        </form>
      </div>
    </div>
  </div>
</div>

<?php $extraJs = "<script>
function toggleRecord(id, active, module) {
  pcAjax('departments.php?m='+module, {action:'toggle',id:id,active:active}, function(r) {
    showToast(r.message,'success');
  });
}
function deleteRecord(id, name, module) {
  document.getElementById('deleteMsg').textContent = 'Delete \"'+name+'\"? This cannot be undone.';
  document.getElementById('deleteId').value = id;
  document.getElementById('deleteForm').action = 'departments.php?m='+module;
  new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// ── Map Picker for Locations ──────────────────────────────────
var mapModal, mapInstance, markerInstance;

function openMapPicker() {
  var latVal = parseFloat(document.getElementById('inp_lat').value) || 13.0827;
  var lngVal = parseFloat(document.getElementById('inp_lng').value) || 80.2707;
  var radius = parseInt(document.getElementById('inp_radius').value) || 25;

  if (!mapModal) {
    // Create modal HTML dynamically
    var html = '<div class=\"modal fade\" id=\"mapPickerModal\" tabindex=\"-1\">' +
      '<div class=\"modal-dialog modal-lg\">' +
      '<div class=\"modal-content\">' +
      '<div class=\"modal-header py-2\">' +
      '<h6 class=\"modal-title\"><i class=\"ti ti-map-pin me-1\"></i>Pick Office Location</h6>' +
      '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +
      '</div>' +
      '<div class=\"modal-body p-0\">' +
      '<div class=\"p-2 bg-light border-bottom\">' +
      '<small class=\"text-muted\"><i class=\"ti ti-info-circle me-1\"></i>Click on the map to set office location. Blue circle shows the geofence radius.</small>' +
      '</div>' +
      '<div id=\"mapDiv\" style=\"height:420px;\"></div>' +
      '</div>' +
      '<div class=\"modal-footer py-2\">' +
      '<button type=\"button\" class=\"btn btn-sm btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button>' +
      '<button type=\"button\" class=\"btn btn-sm btn-pc\" onclick=\"confirmMapLocation()\"><i class=\"ti ti-check me-1\"></i>Use This Location</button>' +
      '</div>' +
      '</div></div></div>';
    document.body.insertAdjacentHTML('beforeend', html);
    mapModal = new bootstrap.Modal(document.getElementById('mapPickerModal'));
  }

  mapModal.show();

  // Load Leaflet if not loaded
  if (typeof L === 'undefined') {
    var css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
    document.head.appendChild(css);

    var js = document.createElement('script');
    js.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
    js.onload = function() { initMap(latVal, lngVal, radius); };
    document.head.appendChild(js);
  } else {
    setTimeout(function() { initMap(latVal, lngVal, radius); }, 100);
  }
}

function initMap(lat, lng, radius) {
  if (mapInstance) {
    mapInstance.remove();
    mapInstance = null;
    markerInstance = null;
  }
  mapInstance = L.map('mapDiv').setView([lat, lng], 17);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(mapInstance);

  // Marker
  markerInstance = L.marker([lat, lng], {draggable: true}).addTo(mapInstance);
  var circle = L.circle([lat, lng], {radius: radius, color: '#0d6efd', fillOpacity: 0.15}).addTo(mapInstance);

  markerInstance.on('dragend', function(e) {
    var pos = e.target.getLatLng();
    circle.setLatLng(pos);
  });

  mapInstance.on('click', function(e) {
    markerInstance.setLatLng(e.latlng);
    circle.setLatLng(e.latlng);
  });

  // Update circle when radius changes
  document.getElementById('inp_radius').oninput = function() {
    circle.setRadius(parseInt(this.value) || 25);
  };
}

function confirmMapLocation() {
  if (!markerInstance) return;
  var pos = markerInstance.getLatLng();
  document.getElementById('inp_lat').value = pos.lat.toFixed(8);
  document.getElementById('inp_lng').value = pos.lng.toFixed(8);
  mapModal.hide();
  showToast('Location set: ' + pos.lat.toFixed(6) + ', ' + pos.lng.toFixed(6), 'success');
}
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
