<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Rwandan Insurance List ----------------
$insuranceOptions = [
    "Sonarwa Insurance","Soras Insurance","Prime Insurance","Radiant Insurance",
    "RSSB (RAMA)","ITM Africa Ltd","Cogebanque Assurance","ADEPR","ALU","BK","MIS UR","BRITAM","Eden Care","ASCOMA Rwanda","CMU Africa","King David","UBF","Uzima Checken","PSF","MUA","New Life Ministries (Dream)","MMI","Private",
    "Trinity Insurance","AXA Assurance Rwanda","Liberty Life Rwanda","UAP Old Mutual Rwanda","BRD Insurance","Sanlam"
];

// ---------------- Handle CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

    $facility_id = $_SESSION['facility_id']; // <-- Always use session, remove dropdown

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        $stmt = $pdo->prepare("INSERT INTO insurance_partners (facility_id, name, description, status) VALUES (?, ?, ?, 'enabled')");
        $stmt->execute([$facility_id, $name, $description]);

        $_SESSION['flash'] = ['message'=>'Insurance partner added successfully!','color'=>'#28a745'];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        $id = intval($_POST['id']);
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        $stmt = $pdo->prepare("UPDATE insurance_partners SET name=?, description=? WHERE id=? AND facility_id=?");
        $stmt->execute([$name, $description, $id, $facility_id]);

        $_SESSION['flash'] = ['message'=>'Insurance partner updated successfully!','color'=>'#007bff'];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- TOGGLE ENABLE/DISABLE ----------
    if (isset($_POST['toggle'])) {
        $id = intval($_POST['id']);
        $currentStatus = $_POST['current_status'] === 'enabled' ? 'disabled' : 'enabled';

        $stmt = $pdo->prepare("UPDATE insurance_partners SET status=? WHERE id=? AND facility_id=?");
        $stmt->execute([$currentStatus, $id, $facility_id]);

        $statusText = $currentStatus=='enabled' ? 'Insurance partner enabled!' : 'Insurance partner disabled!';
        $statusColor = $currentStatus=='enabled' ? '#28a745' : '#dc3545';
        $_SESSION['flash'] = ['message'=>$statusText,'color'=>$statusColor];

        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Insurance Partners ----------------
$stmt = $pdo->prepare("SELECT * FROM insurance_partners WHERE facility_id=? ORDER BY id DESC");
$stmt->execute([$_SESSION['facility_id']]);
$partners = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Insurance Partners</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addPartnerModal">Add Insurance Partner</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th><th>Insurance Partner</th><th>Description</th><th>Status</th><th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($partners as $p): ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td><?= htmlspecialchars($p['name']) ?></td>
                    <td><?= htmlspecialchars($p['description']) ?></td>
                    <td style="color: <?= $p['status']=='enabled'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                        <?= ucfirst($p['status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $p['id'] ?>">Edit</button>

                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $p['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle" class="btn btn-sm <?= $p['status']=='enabled'?'btn-secondary':'btn-success' ?>">
                          <?= $p['status']=='enabled'?'Disable':'Enable' ?>
                        </button>
                      </form>
                    </td>
                  </tr>

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editModal<?= $p['id'] ?>" tabindex="-1">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <form method="post">
                          <input type="hidden" name="csrf" value="<?= $csrf ?>">
                          <input type="hidden" name="id" value="<?= $p['id'] ?>">

                          <div class="modal-header">
                            <h4>Edit Insurance Partner</h4>
                          </div>
                          <div class="modal-body">
                            <label>Insurance Partner Name *</label>
                            <input type="text" name="name" class="form-control" list="insuranceListEdit<?= $p['id'] ?>" 
                                   value="<?= htmlspecialchars($p['name']) ?>" required placeholder="Type or select insurance partner">
                            <datalist id="insuranceListEdit<?= $p['id'] ?>">
                              <?php foreach($insuranceOptions as $ins): ?>
                                <option value="<?= htmlspecialchars($ins) ?>"><?= htmlspecialchars($ins) ?></option>
                              <?php endforeach; ?>
                            </datalist>

                            <label>Description</label>
                            <textarea name="description" class="form-control"><?= htmlspecialchars($p['description']) ?></textarea>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
                            <button type="submit" name="update" class="btn btn-outline-primary btn-md">Update</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>

                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Partner Modal -->
<div class="modal fade" id="addPartnerModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add Insurance Partner</label>
        </div>
        <div class="modal-body">
          <label>Insurance Partner Name *</label>
          <input type="text" name="name" class="form-control" list="insuranceList" 
                 required placeholder="Type or select insurance partner" autocomplete="off">
          <datalist id="insuranceList">
            <?php foreach($insuranceOptions as $ins): ?>
              <option value="<?= htmlspecialchars($ins) ?>"><?= htmlspecialchars($ins) ?></option>
            <?php endforeach; ?>
          </datalist>

          <label>Description</label>
          <textarea name="description" class="form-control" maxlength="255" placeholder="Optional description"></textarea>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>


<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

/* Style for datalist suggestions */
input::-webkit-calendar-picker-indicator {
  display: none !important;
}

.form-control {
  height: 45px;
}

textarea.form-control {
  height: auto;
  min-height: 80px;
}
</style>

<script>
// Auto-complete enhancement
document.addEventListener('DOMContentLoaded', function() {
  // Focus on insurance input when modal opens
  $('#addPartnerModal').on('shown.bs.modal', function () {
    $(this).find('input[name="name"]').focus();
  });
  
  // Focus on insurance input when edit modal opens
  $('[id^="editModal"]').on('shown.bs.modal', function () {
    $(this).find('input[name="name"]').focus().select();
  });
  
  // Prevent form submission on Enter key in input field (let user choose from dropdown)
  document.querySelectorAll('input[list]').forEach(input => {
    input.addEventListener('keydown', function(e) {
      if (e.key === 'Enter' && !this.getAttribute('data-selected')) {
        e.preventDefault();
      }
    });
    
    // Mark when user selects from dropdown
    input.addEventListener('input', function() {
      const options = document.getElementById(this.getAttribute('list')).options;
      for (let option of options) {
        if (option.value === this.value) {
          this.setAttribute('data-selected', 'true');
          return;
        }
      }
      this.removeAttribute('data-selected');
    });
  });
});
</script>

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

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload = function() {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
    toast.innerText = '<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>