<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$pagetitle = 'Panchayats';
$activemenu = 'panchayats';
require 'header.php';
?>

<div class="dfp-card">
  <h3>Panchayats <button class="btn btn-sm" style="float:right;" onclick="openPanchayatModal()">+ Add Panchayat</button></h3>
  <table id="tblPanchayats" class="dfp-table" style="width:100%;">
    <thead>
      <tr><th>Name</th><th>Code</th><th>Status</th><th>Action</th></tr>
      <tr class="filterrow">
        <th><input class="dfp-colfilter"></th><th><input class="dfp-colfilter"></th><th></th><th></th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<div class="dfp-card">
  <h3>Panchayat Portal Users <button class="btn btn-sm" style="float:right;" onclick="openPanchayatUserModal()">+ Add User</button></h3>
  <table id="tblPanchayatUsers" class="dfp-table" style="width:100%;">
    <thead>
      <tr><th>Name</th><th>Username</th><th>Phone</th><th>Panchayat</th><th>Status</th><th>Action</th></tr>
      <tr class="filterrow">
        <th><input class="dfp-colfilter"></th><th><input class="dfp-colfilter"></th><th><input class="dfp-colfilter"></th>
        <th><input class="dfp-colfilter"></th><th></th><th></th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<!-- Panchayat modal -->
<div id="panchayatModal" class="dfpmodal" style="display:none;">
  <div class="dfpmodalbox">
    <h3 id="panchayatModalTitle">Add Panchayat</h3>
    <form id="frmPanchayat">
      <input type="hidden" name="id" id="pId">
      <div class="dfp-formgroup"><label>Name</label><input type="text" name="name" id="pName" required></div>
      <div class="dfp-formgroup"><label>Code</label><input type="text" name="code" id="pCode" required></div>
      <button type="submit" class="btn">Save</button>
      <button type="button" class="btn btn-outline" onclick="closeModal('panchayatModal')">Cancel</button>
    </form>
  </div>
</div>

<!-- Panchayat user modal -->
<div id="panchayatUserModal" class="dfpmodal" style="display:none;">
  <div class="dfpmodalbox">
    <h3 id="panchayatUserModalTitle">Add Panchayat User</h3>
    <form id="frmPanchayatUser">
      <input type="hidden" name="id" id="puId">
      <div class="dfp-formgroup"><label>Name</label><input type="text" name="name" id="puName" required></div>
      <div class="dfp-formgroup"><label>Username</label><input type="text" name="username" id="puUsername" required></div>
      <div class="dfp-formgroup"><label>Phone</label><input type="text" name="phone" id="puPhone" required></div>
      <div class="dfp-formgroup">
        <label>Panchayat</label>
        <select name="panchayatid" id="puPanchayatId" required></select>
      </div>
      <div class="dfp-formgroup" id="puPasswordWrap"><label>Password</label><input type="password" name="password" id="puPassword"></div>
      <button type="submit" class="btn">Save</button>
      <button type="button" class="btn btn-outline" onclick="closeModal('panchayatUserModal')">Cancel</button>
    </form>
  </div>
</div>

<style>
.dfpmodal { position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:2000; }
.dfpmodalbox { background:#fff; max-width:420px; margin:60px auto; padding:16px; border-radius:4px; }
</style>

<?php require 'footer.php'; ?>
<script>
var tblPanchayats, tblPanchayatUsers, panchayatOptions = [];

function closeModal(id) { $('#' + id).hide(); }

function loadPanchayatOptions(callback) {
  $.getJSON('ajax_admin_panchayat.php', { action: 'listall' }, function (resp) {
    panchayatOptions = resp.data || [];
    var sel = $('#puPanchayatId').empty();
    panchayatOptions.forEach(function (p) {
      sel.append('<option value="' + p.id + '">' + p.name + '</option>');
    });
    if (callback) { callback(); }
  });
}

function openPanchayatModal(row) {
  $('#frmPanchayat')[0].reset();
  $('#pId').val(row ? row.id : '');
  $('#pName').val(row ? row.name : '');
  $('#pCode').val(row ? row.code : '');
  $('#panchayatModalTitle').text(row ? 'Edit Panchayat' : 'Add Panchayat');
  $('#panchayatModal').show();
}

function openPanchayatUserModal(row) {
  loadPanchayatOptions(function () {
    $('#frmPanchayatUser')[0].reset();
    $('#puId').val(row ? row.id : '');
    $('#puName').val(row ? row.name : '');
    $('#puUsername').val(row ? row.username : '');
    $('#puPhone').val(row ? row.phone : '');
    if (row) { $('#puPanchayatId').val(row.panchayatid); }
    $('#puPasswordWrap label').text(row ? 'New Password (leave blank to keep unchanged)' : 'Password');
    $('#puPasswordWrap input').prop('required', !row);
    $('#panchayatUserModalTitle').text(row ? 'Edit Panchayat User' : 'Add Panchayat User');
    $('#panchayatUserModal').show();
  });
}

function toggleStatus(action, id, reload) {
  $.post('ajax_admin_panchayat.php', { action: action, id: id }, function (resp) {
    dfpToast(resp.message, resp.success ? 'success' : 'error');
    if (resp.success) { reload(); }
  }, 'json');
}

$(function () {
  tblPanchayats = $('#tblPanchayats').DataTable({
    ajax: { url: 'ajax_admin_panchayat.php', data: { action: 'list' }, dataSrc: 'data' },
    columns: [
      { data: 'name' },
      { data: 'code' },
      { data: 'isdeleted', render: function (d) { return d == 1 ? '<span class="badge badge-inactive">Inactive</span>' : '<span class="badge badge-approved">Active</span>'; } },
      { data: null, orderable: false, render: function (d) {
          return '<button class="btn btn-sm btn-outline" onclick=\'openPanchayatModal(' + JSON.stringify(d) + ')\'>Edit</button> ' +
                 '<button class="btn btn-sm btn-danger" onclick="toggleStatus(\'toggledelete\',' + d.id + ',reloadPanchayats)">' + (d.isdeleted == 1 ? 'Restore' : 'Disable') + '</button>';
        } }
    ]
  });

  tblPanchayatUsers = $('#tblPanchayatUsers').DataTable({
    ajax: { url: 'ajax_admin_panchayat.php', data: { action: 'listusers' }, dataSrc: 'data' },
    columns: [
      { data: 'name' }, { data: 'username' }, { data: 'phone' }, { data: 'panchayatname' },
      { data: 'isactive', render: function (d) { return d == 1 ? '<span class="badge badge-approved">Active</span>' : '<span class="badge badge-inactive">Inactive</span>'; } },
      { data: null, orderable: false, render: function (d) {
          return '<button class="btn btn-sm btn-outline" onclick=\'openPanchayatUserModal(' + JSON.stringify(d) + ')\'>Edit</button> ' +
                 '<button class="btn btn-sm btn-danger" onclick="toggleStatus(\'toggleuserstatus\',' + d.id + ',reloadPanchayatUsers)">' + (d.isactive == 1 ? 'Deactivate' : 'Activate') + '</button>';
        } }
    ]
  });

  dfpEnableColumnFilters('#tblPanchayats');
  dfpEnableColumnFilters('#tblPanchayatUsers');

  $('#frmPanchayat').on('submit', function (e) {
    e.preventDefault();
    $.post('ajax_admin_panchayat.php', $(this).serialize() + '&action=save', function (resp) {
      dfpToast(resp.message, resp.success ? 'success' : 'error');
      if (resp.success) { closeModal('panchayatModal'); reloadPanchayats(); }
    }, 'json');
  });

  $('#frmPanchayatUser').on('submit', function (e) {
    e.preventDefault();
    $.post('ajax_admin_panchayat.php', $(this).serialize() + '&action=saveuser', function (resp) {
      dfpToast(resp.message, resp.success ? 'success' : 'error');
      if (resp.success) { closeModal('panchayatUserModal'); reloadPanchayatUsers(); }
    }, 'json');
  });
});

function reloadPanchayats() { tblPanchayats.ajax.reload(null, false); }
function reloadPanchayatUsers() { tblPanchayatUsers.ajax.reload(null, false); }
</script>
<?php require 'footer2.php'; ?>
