<?php
$active = 'users';
$pageTitle = 'Add / Edit User';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

try { $pdo->query("SELECT 1 FROM users LIMIT 1"); } catch (Exception $e) {
  echo "<div class='alert alert-warning'>User tables not found. Run database/user_tables.sql first.</div>";
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$id = (int)($_GET['id'] ?? 0);
$user = ['id' => 0, 'name' => '', 'email' => '', 'phone' => ''];
if ($id) {
  $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
  $stmt->execute([$id]);
  $user = $stmt->fetch();
  if (!$user) {
    echo "<div class='alert alert-danger'>User not found.</div>";
    require_once __DIR__ . '/partials/bottom.php';
    exit;
  }
}

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $phone = preg_replace('/\D+/', '', (string)($_POST['phone'] ?? ''));
  if ($name === '' || $phone === '') {
    $msg = "<div class='alert alert-danger'>Name and phone are required.</div>";
  } else {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE (phone=? OR email=?) AND id<>?");
    $stmt->execute([$phone, $email ?: 'x@x.x', $id]);
    if ($stmt->fetch()) {
      $msg = "<div class='alert alert-danger'>Phone or email already exists.</div>";
    } else {
      if ($id) {
        $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, phone=? WHERE id=?");
        $stmt->execute([$name, $email, $phone, $id]);
        $msg = "<div class='alert alert-success'>User updated.</div>";
      } else {
        $stmt = $pdo->prepare("INSERT INTO users (name, email, phone) VALUES (?,?,?)");
        $stmt->execute([$name, $email, $phone]);
        $msg = "<div class='alert alert-success'>User created.</div>";
      }
      header('Location: users.php');
      exit;
    }
  }
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0"><?php echo $id ? 'Edit User' : 'Add User'; ?></h4>
    <div class="text-muted small">User profile for customer app</div>
  </div>
  <a class="btn btn-outline-dark" href="users.php">Back</a>
</div>

<?php echo $msg; ?>

<div class="card p-4">
  <form method="post">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">Name</label>
        <input class="form-control" name="name" required value="<?php echo htmlspecialchars($user['name']); ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Phone</label>
        <input class="form-control" name="phone" required value="<?php echo htmlspecialchars($user['phone']); ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Email</label>
        <input class="form-control" type="email" name="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
      </div>
      <div class="col-12">
        <button class="btn btn-dark" type="submit"><?php echo $id ? 'Update' : 'Create'; ?> User</button>
      </div>
    </div>
  </form>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
