<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../config/db.php';

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add') {
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $ward  = trim($_POST['ward'] ?? '');
        $role  = in_array($_POST['role'] ?? '', ['surveyor','supervisor','admin']) ? $_POST['role'] : 'surveyor';
        $pass  = password_hash($_POST['password'] ?? 'survey123', PASSWORD_BCRYPT);
        try {
            $pdo->prepare('INSERT INTO surveyors (name, email, phone, ward_assigned, role, password_hash) VALUES (?,?,?,?,?,?)')
                ->execute([$name, $email, $phone, $ward, $role, $pass]);
            $msg = 'success';
        } catch (Exception $e) {
            $msg = 'error:' . $e->getMessage();
        }
    } elseif ($_POST['action'] === 'edit') {
        $id    = (int)($_POST['id'] ?? 0);
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $ward  = trim($_POST['ward'] ?? '');
        $role  = in_array($_POST['role'] ?? '', ['surveyor','supervisor','admin']) ? $_POST['role'] : 'surveyor';
        try {
            if (!empty($_POST['password'])) {
                $pass = password_hash($_POST['password'], PASSWORD_BCRYPT);
                $pdo->prepare('UPDATE surveyors SET name=?, email=?, phone=?, ward_assigned=?, role=?, password_hash=? WHERE id=?')
                    ->execute([$name, $email, $phone, $ward, $role, $pass, $id]);
            } else {
                $pdo->prepare('UPDATE surveyors SET name=?, email=?, phone=?, ward_assigned=?, role=? WHERE id=?')
                    ->execute([$name, $email, $phone, $ward, $role, $id]);
            }
            $msg = 'updated';
        } catch (Exception $e) {
            $msg = 'error:' . $e->getMessage();
        }
    } elseif ($_POST['action'] === 'toggle') {
        $pdo->prepare('UPDATE surveyors SET is_active = NOT is_active WHERE id = ?')
            ->execute([(int)$_POST['id']]);
    } elseif ($_POST['action'] === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        // Guard: don't delete a surveyor who already has surveys (keep data integrity) — deactivate instead
        $cnt = $pdo->prepare('SELECT COUNT(*) FROM surveys WHERE surveyor_id = ?');
        $cnt->execute([$id]);
        if ((int)$cnt->fetchColumn() > 0) {
            $pdo->prepare('UPDATE surveyors SET is_active = 0 WHERE id = ?')->execute([$id]);
            $msg = 'deactivated_has_surveys';
        } else {
            $pdo->prepare('DELETE FROM surveyors WHERE id = ?')->execute([$id]);
            $msg = 'deleted';
        }
    }
}

$stmt = $pdo->query("SELECT * FROM surveyors ORDER BY role, name");
$surveyors = $stmt ? $stmt->fetchAll() : [];

$roleColor  = ['admin'=>'bg-red-100 text-red-700','supervisor'=>'bg-amber-100 text-amber-700','surveyor'=>'bg-blue-100 text-blue-700'];
$roleCount  = ['admin'=>0,'supervisor'=>0,'surveyor'=>0];
foreach ($surveyors as $s) $roleCount[$s['role']] = ($roleCount[$s['role']] ?? 0) + 1;
?>

<div class="flex items-center justify-between mb-6">
  <div>
    <h2 class="text-xl font-bold text-slate-800">Surveyors</h2>
    <p class="text-sm text-slate-500 mt-0.5"><?= count($surveyors) ?> registered users</p>
  </div>
  <!-- Alpine modal trigger -->
  <button @click="$dispatch('open-modal')"
          class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700
                 text-white text-sm font-medium rounded-xl transition-colors shadow-sm">
    + Add Surveyor
  </button>
</div>

<?php if ($msg === 'success'): ?>
<div class="mb-4 flex items-center gap-3 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">
  ✅ Surveyor added successfully.
</div>
<?php elseif ($msg === 'updated'): ?>
<div class="mb-4 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">✅ Surveyor updated.</div>
<?php elseif ($msg === 'deleted'): ?>
<div class="mb-4 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">✅ Surveyor deleted.</div>
<?php elseif ($msg === 'deactivated_has_surveys'): ?>
<div class="mb-4 px-4 py-3 bg-amber-50 border border-amber-200 rounded-xl text-amber-700 text-sm">⚠️ Surveyor has surveys — deactivated instead of deleted (keeps survey data).</div>
<?php elseif (str_starts_with($msg, 'error:')): ?>
<div class="mb-4 px-4 py-3 bg-red-50 border border-red-200 rounded-xl text-red-700 text-sm">
  ⚠️ <?= htmlspecialchars(substr($msg, 6)) ?>
</div>
<?php endif ?>

<!-- Stats row -->
<div class="grid grid-cols-3 gap-4 mb-5">
  <?php foreach (['admin'=>'🔑 Admins','supervisor'=>'👁 Supervisors','surveyor'=>'📋 Surveyors'] as $role => $label): ?>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 text-center">
    <div class="text-2xl font-bold text-slate-800"><?= $roleCount[$role] ?></div>
    <div class="text-xs text-slate-500 mt-0.5"><?= $label ?></div>
  </div>
  <?php endforeach ?>
</div>

<!-- Table -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
  <div class="overflow-x-auto">
    <table class="w-full text-sm">
      <thead>
        <tr class="bg-gray-50 text-xs text-slate-500 uppercase tracking-wide border-b border-gray-100">
          <th class="px-5 py-3 text-left font-medium">#</th>
          <th class="px-5 py-3 text-left font-medium">Name</th>
          <th class="px-5 py-3 text-left font-medium">Email</th>
          <th class="px-5 py-3 text-left font-medium">Phone</th>
          <th class="px-5 py-3 text-left font-medium">Ward</th>
          <th class="px-5 py-3 text-left font-medium">Role</th>
          <th class="px-5 py-3 text-left font-medium">Status</th>
          <th class="px-5 py-3 text-left font-medium"></th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php foreach ($surveyors as $s): ?>
        <tr class="hover:bg-gray-50 transition-colors">
          <td class="px-5 py-3 text-slate-400 text-xs"><?= $s['id'] ?></td>
          <td class="px-5 py-3 font-medium text-slate-700"><?= htmlspecialchars($s['name']) ?></td>
          <td class="px-5 py-3 text-slate-500"><?= htmlspecialchars($s['email']) ?></td>
          <td class="px-5 py-3 text-slate-500"><?= htmlspecialchars($s['phone']) ?></td>
          <td class="px-5 py-3 text-slate-600"><?= htmlspecialchars($s['ward_assigned']) ?></td>
          <td class="px-5 py-3">
            <span class="inline-flex px-2 py-0.5 rounded-full text-xs font-medium <?= $roleColor[$s['role']] ?? 'bg-gray-100 text-gray-600' ?>">
              <?= ucfirst($s['role']) ?>
            </span>
          </td>
          <td class="px-5 py-3">
            <?php if ($s['is_active']): ?>
              <span class="inline-flex items-center gap-1 text-green-600 text-xs font-medium">
                <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Active
              </span>
            <?php else: ?>
              <span class="inline-flex items-center gap-1 text-slate-400 text-xs font-medium">
                <span class="w-1.5 h-1.5 rounded-full bg-gray-300"></span> Inactive
              </span>
            <?php endif ?>
          </td>
          <td class="px-5 py-3">
            <div class="flex items-center gap-2">
              <button type="button"
                @click='$dispatch("edit-surveyor", <?= htmlspecialchars(json_encode([
                    "id"=>$s["id"],"name"=>$s["name"],"email"=>$s["email"],
                    "phone"=>$s["phone"],"ward"=>$s["ward_assigned"],"role"=>$s["role"]
                ]), ENT_QUOTES) ?>)'
                class="text-xs px-3 py-1.5 border border-blue-200 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
                Edit
              </button>
              <form method="post" class="inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= $s['id'] ?>">
                <button class="text-xs px-3 py-1.5 border rounded-lg transition-colors
                               <?= $s['is_active']
                                 ? 'border-amber-200 text-amber-600 hover:bg-amber-50'
                                 : 'border-green-200 text-green-600 hover:bg-green-50' ?>">
                  <?= $s['is_active'] ? 'Deactivate' : 'Activate' ?>
                </button>
              </form>
              <form method="post" class="inline"
                    onsubmit="return confirm('Delete <?= htmlspecialchars(addslashes($s['name']), ENT_QUOTES) ?>? (If they have surveys, they will be deactivated instead.)');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $s['id'] ?>">
                <button class="text-xs px-3 py-1.5 border border-red-200 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
                  Delete
                </button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Add Surveyor Modal (Alpine.js) -->
<div x-data="{ open: false }"
     @open-modal.window="open = true"
     x-show="open"
     x-cloak
     class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
  <div @click.outside="open = false"
       class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
    <div class="flex items-center justify-between mb-5">
      <h3 class="text-lg font-bold text-slate-800">Add Surveyor</h3>
      <button @click="open = false" class="text-slate-400 hover:text-slate-700">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>
    <form method="post" class="space-y-4">
      <input type="hidden" name="action" value="add">
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Full Name *</label>
          <input type="text" name="name" required
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Phone</label>
          <input type="text" name="phone"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">Email *</label>
        <input type="email" name="email" required
               class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Ward Assigned</label>
          <input type="text" name="ward"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Role</label>
          <select name="role"
                  class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white">
            <option value="surveyor">Surveyor</option>
            <option value="supervisor">Supervisor</option>
            <option value="admin">Admin</option>
          </select>
        </div>
      </div>
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">Password *</label>
        <input type="password" name="password" placeholder="Min 8 chars" required
               class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        <p class="text-xs text-slate-400 mt-1">Surveyor will use this to login on the app</p>
      </div>
      <div class="flex gap-3 pt-2">
        <button type="button" @click="open = false"
                class="flex-1 px-4 py-2.5 border border-gray-200 text-slate-600 hover:bg-gray-50 text-sm font-medium rounded-xl transition-colors">
          Cancel
        </button>
        <button type="submit"
                class="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors">
          Add Surveyor
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Surveyor Modal (Alpine.js) -->
<div x-data="{ open: false, f: { id:'', name:'', email:'', phone:'', ward:'', role:'surveyor' } }"
     @edit-surveyor.window="f = Object.assign({password:''}, $event.detail); open = true"
     x-show="open" x-cloak
     class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
  <div @click.outside="open = false" class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
    <div class="flex items-center justify-between mb-5">
      <h3 class="text-lg font-bold text-slate-800">Edit Surveyor</h3>
      <button @click="open = false" class="text-slate-400 hover:text-slate-700">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>
    <form method="post" class="space-y-4">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" :value="f.id">
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Full Name *</label>
          <input type="text" name="name" x-model="f.name" required
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Phone</label>
          <input type="text" name="phone" x-model="f.phone"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">Email *</label>
        <input type="email" name="email" x-model="f.email" required
               class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Ward Assigned</label>
          <input type="text" name="ward" x-model="f.ward"
                 class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Role</label>
          <select name="role" x-model="f.role"
                  class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white">
            <option value="surveyor">Surveyor</option>
            <option value="supervisor">Supervisor</option>
            <option value="admin">Admin</option>
          </select>
        </div>
      </div>
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">New Password</label>
        <input type="password" name="password" x-model="f.password" placeholder="Leave blank to keep current"
               class="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>
      <div class="flex gap-3 pt-2">
        <button type="button" @click="open = false"
                class="flex-1 px-4 py-2.5 border border-gray-200 text-slate-600 hover:bg-gray-50 text-sm font-medium rounded-xl transition-colors">
          Cancel
        </button>
        <button type="submit"
                class="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors">
          Save Changes
        </button>
      </div>
    </form>
  </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
