<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

$admin = current_user();

function upload_user_photo(array $file): ?string {
  if (empty($file['name']) || (int)$file['error'] !== 0) return null;

  $tmp = $file['tmp_name'] ?? '';
  if (!$tmp || !is_uploaded_file($tmp)) return null;

  $mime = mime_content_type($tmp);
  if (!in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
    throw new Exception('Photo must be JPG, PNG, or WEBP.');
  }

  $ext = match ($mime) {
    'image/png'  => 'png',
    'image/webp' => 'webp',
    default      => 'jpg'
  };

  $dirFs = realpath(__DIR__ . '/..');
  if (!$dirFs) throw new Exception('Upload directory path error.');

  $uploadDir = $dirFs . '/uploads/users';
  if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);

  $safeName = 'user_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
  $destFs = $uploadDir . '/' . $safeName;

  if (!move_uploaded_file($tmp, $destFs)) {
    throw new Exception('Failed to upload photo.');
  }

  return '/uploads/users/' . $safeName;
}

$id = (int)($_GET['id'] ?? 0);
if ($id < 1) redirect('customers.php');

/* LOAD CUSTOMER */
$st = $conn->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
$st->bind_param("i", $id);
$st->execute();
$user = $st->get_result()->fetch_assoc();
if (!$user) { flash('err','Customer not found'); redirect('customers.php'); }

if (is_post()) {
  csrf_verify();

  $name   = trim($_POST['full_name'] ?? '');
  $email  = trim($_POST['email'] ?? '');
  $phone  = trim($_POST['phone'] ?? '');
  $dob    = $_POST['dob'] ?? null;
  $gender = $_POST['gender'] ?? null;
  $job    = trim($_POST['occupation'] ?? '');
  $addr   = trim($_POST['address'] ?? '');

  $newPass = trim($_POST['new_password'] ?? '');
  $newPin  = trim($_POST['new_pin'] ?? '');

  if (!$name || !$email) {
    flash('err','Full name and email are required.');
    redirect("customer_edit.php?id=$id");
  }

  try {

    $photoPath = $user['photo'] ?? null;
    if (!empty($_FILES['photo']['name'])) {
      $photoPath = upload_user_photo($_FILES['photo']);
    }

    /* Update main fields */
    $st = $conn->prepare("
      UPDATE users
      SET full_name=?, email=?, phone=?, dob=?, gender=?, occupation=?, address=?, photo=?
      WHERE id=?
    ");
    $st->bind_param("ssssssssi", $name, $email, $phone, $dob, $gender, $job, $addr, $photoPath, $id);
    $st->execute();

    /* Optional reset password */
    if ($newPass !== '') {
      $hash = password_hash($newPass, PASSWORD_DEFAULT);
      $st = $conn->prepare("UPDATE users SET password_hash=? WHERE id=?");
      $st->bind_param("si", $hash, $id);
      $st->execute();
    }

    /* Optional reset PIN */
    if ($newPin !== '') {
      if (!ctype_digit($newPin) || strlen($newPin) < 4 || strlen($newPin) > 6) {
        throw new Exception('PIN must be 4–6 digits.');
      }
      $pinHash = password_hash($newPin, PASSWORD_DEFAULT);
      $pinTemp = 1; // force change on next login if you want
      $st = $conn->prepare("UPDATE users SET pin_hash=?, pin_temp=? WHERE id=?");
      $st->bind_param("sii", $pinHash, $pinTemp, $id);
      $st->execute();
    }

    /* AUDIT (INLINE) */
    $meta = json_encode(['user_id'=>$id,'updated'=>true], JSON_UNESCAPED_SLASHES);
    $ip = client_ip();
    $action = 'ADMIN_EDIT_CUSTOMER';

    $st = $conn->prepare("INSERT INTO audit_logs (actor_id, action, meta, ip) VALUES (?, ?, ?, ?)");
    $st->bind_param("isss", $admin['id'], $action, $meta, $ip);
    $st->execute();

    flash('msg','Customer updated successfully.');
    redirect("customer_edit.php?id=$id");

  } catch (Throwable $e) {
    flash('err', $e->getMessage());
    redirect("customer_edit.php?id=$id");
  }
}

$title = 'Edit Customer — Admin';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';

$msg = flash('msg');
$err = flash('err');

$photo = $user['photo'] ?: '/uploads/profile/avatar.png';
?>

<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0">Edit Customer</h3>
    <a href="customers.php" class="btn btn-sm btn-outline-secondary">Back</a>
  </div>

  <?php if ($msg): ?><div class="alert alert-success"><?= e($msg) ?></div><?php endif; ?>
  <?php if ($err): ?><div class="alert alert-danger"><?= e($err) ?></div><?php endif; ?>

  <div class="card ab-card p-4" style="max-width:950px">
    <form method="post" enctype="multipart/form-data">
      <?= csrf_field() ?>

      <div class="d-flex align-items-center gap-3 mb-4">
        <img src="<?= e($photo) ?>" class="rounded-circle border" style="width:90px;height:90px;object-fit:cover">
        <div>
          <div class="fw-bold"><?= e($user['full_name']) ?></div>
          <div class="text-muted small"><?= e($user['email']) ?></div>
        </div>
      </div>

      <div class="row g-3">

        <div class="col-md-6">
          <label class="form-label">Full Name</label>
          <input class="form-control" name="full_name" value="<?= e($user['full_name'] ?? '') ?>" required>
        </div>

        <div class="col-md-6">
          <label class="form-label">Email</label>
          <input type="email" class="form-control" name="email" value="<?= e($user['email'] ?? '') ?>" required>
        </div>

        <div class="col-md-4">
          <label class="form-label">Phone</label>
          <input class="form-control" name="phone" value="<?= e($user['phone'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Date of Birth</label>
          <input type="date" class="form-control" name="dob" value="<?= e($user['dob'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Gender</label>
          <select class="form-select" name="gender">
            <option value="">— Select —</option>
            <option value="male"   <?= ($user['gender'] ?? '')==='male'?'selected':'' ?>>Male</option>
            <option value="female" <?= ($user['gender'] ?? '')==='female'?'selected':'' ?>>Female</option>
            <option value="other"  <?= ($user['gender'] ?? '')==='other'?'selected':'' ?>>Other</option>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label">Occupation</label>
          <input class="form-control" name="occupation" value="<?= e($user['occupation'] ?? '') ?>">
        </div>

        <div class="col-md-6">
          <label class="form-label">Address</label>
          <input class="form-control" name="address" value="<?= e($user['address'] ?? '') ?>">
        </div>

        <div class="col-md-6">
          <label class="form-label">Replace Photo (optional)</label>
          <input type="file" class="form-control" name="photo" accept="image/jpeg,image/png,image/webp">
        </div>

        <div class="col-md-6"></div>

        <div class="col-md-6">
          <label class="form-label">Set New Password (optional)</label>
          <input class="form-control" name="new_password" placeholder="Leave blank to keep current">
        </div>

        <div class="col-md-6">
          <label class="form-label">Set New PIN (optional, 4–6 digits)</label>
          <input class="form-control" name="new_pin" maxlength="6" inputmode="numeric" placeholder="Leave blank to keep current">
        </div>

      </div>

      <div class="mt-4">
        <button class="btn ab-btn text-white">Save Changes</button>
        <a href="customer_view.php?id=<?= (int)$id ?>" class="btn btn-outline-secondary ms-2">View Profile</a>
      </div>

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

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
