<?php
// hps_salespersons.php
session_start();
require "db.php";

error_reporting(E_ALL);
ini_set('display_errors', 1);

function e($v){
    return htmlspecialchars((string)($v ?? ''));
}

/* =========================
   SAVE (ADD / UPDATE)
========================= */
if(isset($_POST['save'])){

    $id      = (int)($_POST['id'] ?? 0);
    $name    = mysqli_real_escape_string($conn,$_POST['name'] ?? '');
    $mobile  = mysqli_real_escape_string($conn,$_POST['mobile'] ?? '');
    $address = mysqli_real_escape_string($conn,$_POST['address'] ?? '');
    $status  = mysqli_real_escape_string($conn,$_POST['status'] ?? 'Active');

    if($name != ''){

        if($id > 0){
            mysqli_query($conn,"
                UPDATE hps_salespersons
                SET name='$name',
                    mobile='$mobile',
                    address='$address',
                    status='$status'
                WHERE id=$id
            ");
        }else{
            mysqli_query($conn,"
                INSERT INTO hps_salespersons
                (name, mobile, address, status)
                VALUES
                ('$name','$mobile','$address','$status')
            ");
        }
    }

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

    exit;
}

/* =========================
   DELETE
========================= */
if(isset($_GET['del']) && is_numeric($_GET['del'])){
    $id = (int)$_GET['del'];

    mysqli_query($conn,"
        DELETE FROM hps_salespersons
        WHERE id=$id
    ");

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

    exit;
}

/* =========================
   FETCH FOR EDIT
========================= */
$edit = null;
if(isset($_GET['edit']) && is_numeric($_GET['edit'])){
    $id = (int)$_GET['edit'];
    $edit = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT * FROM hps_salespersons WHERE id=$id
    "));
}

/* =========================
   FETCH ALL
========================= */
$list = mysqli_query($conn,"
    SELECT *
    FROM hps_salespersons
    ORDER BY id DESC
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Manage Salespersons</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container py-4">

<h4 class="mb-3">Salesperson Management</h4>

<button class="btn btn-primary btn-sm mb-3"
        data-bs-toggle="modal"
        data-bs-target="#formModal">
    + Add Salesperson
</button>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Mobile</th>
    <th>Address</th>
    <th>Status</th>
    <th width="150">Action</th>
</tr>
</thead>
<tbody>

<?php
$i=1;
if(!$list || mysqli_num_rows($list)==0){
    echo "<tr><td colspan='6' class='text-center text-muted'>No records found</td></tr>";
}

while($r=mysqli_fetch_assoc($list)):
?>

<tr>
    <td><?= $i++ ?></td>
    <td><?= e($r['name']) ?></td>
    <td><?= e($r['mobile']) ?></td>
    <td><?= e($r['address']) ?></td>
    <td>
        <span class="badge <?= ($r['status']=='Active')?'bg-success':'bg-secondary' ?>">
            <?= e($r['status']) ?>
        </span>
    </td>
    <td>
        <a href="?edit=<?= $r['id'] ?>"
           class="btn btn-sm btn-warning">
           Edit
        </a>

        <a href="?del=<?= $r['id'] ?>"
           onclick="return confirm('Delete this salesperson?')"
           class="btn btn-sm btn-danger">
           Delete
        </a>
    </td>
</tr>

<?php endwhile; ?>

</tbody>
</table>

</div>


<!-- MODAL -->
<div class="modal fade"
     id="formModal"
     tabindex="-1"
     aria-hidden="true">

  <div class="modal-dialog">
    <div class="modal-content">

      <form method="post" action="<?= basename(__FILE__) ?>">

        <div class="modal-header">
          <h5 class="modal-title">
              <?= $edit ? 'Edit' : 'Add' ?> Salesperson
          </h5>
          <a href="<?= basename(__FILE__) ?>" class="btn-close"></a>
        </div>

        <div class="modal-body">

          <input type="hidden" name="id"
                 value="<?= e($edit['id'] ?? '') ?>">

          <div class="mb-2">
              <label class="form-label small">Name</label>
              <input type="text"
                     name="name"
                     required
                     value="<?= e($edit['name'] ?? '') ?>"
                     class="form-control form-control-sm">
          </div>

          <div class="mb-2">
              <label class="form-label small">Mobile</label>
              <input type="text"
                     name="mobile"
                     value="<?= e($edit['mobile'] ?? '') ?>"
                     class="form-control form-control-sm">
          </div>

          <div class="mb-2">
              <label class="form-label small">Address</label>
              <textarea name="address"
                        class="form-control form-control-sm"><?= e($edit['address'] ?? '') ?></textarea>
          </div>

          <div class="mb-2">
              <label class="form-label small">Status</label>
              <select name="status"
                      class="form-select form-select-sm">
                  <option value="Active"
                      <?= (!isset($edit['status']) || $edit['status']=='Active')?'selected':'' ?>>
                      Active
                  </option>
                  <option value="Inactive"
                      <?= (isset($edit['status']) && $edit['status']=='Inactive')?'selected':'' ?>>
                      Inactive
                  </option>
              </select>
          </div>

        </div>

        <div class="modal-footer">
          <button type="submit"
                  name="save"
                  class="btn btn-success btn-sm">
              Save
          </button>
        </div>

      </form>

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



<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<?php if($edit): ?>
<script>
var myModal = new bootstrap.Modal(document.getElementById('formModal'));
myModal.show();
</script>
<?php endif; ?>

</body>
</html>
