<?php
session_start();
$page_title = 'My Profile';
$active_nav = 'profile';
include("includes/header.php");

$success = $error = "";

$u_stmt = $conn->prepare("SELECT * FROM users WHERE id=?");
$u_stmt->bind_param("i", $uid);
$u_stmt->execute();
$u = $u_stmt->get_result()->fetch_assoc();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = trim($_POST['name'] ?? '');
    $phone   = trim($_POST['phone'] ?? '');
    $cur_pw  = $_POST['current_password'] ?? '';
    $new_pw  = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if (!$name) {
        $error = "Name is required.";
    } else {
        $conn->begin_transaction();
        try {
            $upd = $conn->prepare("UPDATE users SET name=?, phone=?, updated_at=NOW() WHERE id=?");
            $upd->bind_param("ssi", $name, $phone, $uid);
            $upd->execute();
            $_SESSION['name'] = $name;

            if ($cur_pw) {
                if (!password_verify($cur_pw, $u['password'])) {
                    throw new Exception("Current password is incorrect.");
                }
                if (strlen($new_pw) < 6) {
                    throw new Exception("New password must be at least 6 characters.");
                }
                if ($new_pw !== $confirm) {
                    throw new Exception("Passwords do not match.");
                }
                $hash = password_hash($new_pw, PASSWORD_DEFAULT);
                $pp = $conn->prepare("UPDATE users SET password=? WHERE id=?");
                $pp->bind_param("si", $hash, $uid);
                $pp->execute();
            }
            $conn->commit();
            $success = "Profile updated successfully!";
            $u_stmt->execute();
            $u = $u_stmt->get_result()->fetch_assoc();
        } catch (Exception $e) {
            $conn->rollback();
            $error = $e->getMessage();
        }
    }
}

$role_labels = [
    'restaurant_admin' => 'Restaurant Admin',
    'staff'            => 'Staff',
    'waiter'           => 'Waiter / Waitress',
];
$role_display = $role_labels[$u['role']] ?? ucfirst($u['role']);
$initials = strtoupper(substr($u['name'],0,1)) . (strpos($u['name'],' ')!==false ? strtoupper(substr(strrchr($u['name'],' '),1,1)) : '');
?>

<div style="max-width:560px;margin:0 auto">
  <div style="margin-bottom:28px">
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">My Profile</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Update your personal account information</p>
  </div>

  <!-- Profile Header Card -->
  <div class="card" style="padding:22px;margin-bottom:16px;display:flex;align-items:center;gap:18px;flex-wrap:wrap">
    <div style="width:66px;height:66px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:1.35rem;font-weight:800;color:#fff;flex-shrink:0">
      <?php echo $initials; ?>
    </div>
    <div style="flex:1;min-width:0">
      <div style="font-size:1.1rem;font-weight:800;margin-bottom:2px"><?php echo htmlspecialchars($u['name']); ?></div>
      <div style="font-size:.83rem;color:var(--text-muted);margin-bottom:6px"><?php echo htmlspecialchars($u['email']); ?></div>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <span class="badge badge-primary"><?php echo $role_display; ?></span>
        <span class="badge badge-success"><?php echo htmlspecialchars($__rest_name); ?></span>
      </div>
    </div>
    <div style="text-align:right">
      <div style="font-size:.68rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:.08em;font-weight:700;margin-bottom:3px">Member Since</div>
      <div style="font-size:.875rem;font-weight:700"><?php echo date('M Y', strtotime($u['created_at'])); ?></div>
    </div>
  </div>

  <?php if ($error): ?>
  <div class="alert alert-error">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
    <?php echo htmlspecialchars($error); ?>
  </div>
  <?php endif; ?>
  <?php if ($success): ?>
  <div class="alert alert-success">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    <?php echo $success; ?>
  </div>
  <?php endif; ?>

  <form method="POST">
    <!-- Personal Info -->
    <div class="card" style="margin-bottom:16px">
      <div class="card-header"><h3>Personal Information</h3></div>
      <div class="card-body">
        <div class="form-group">
          <label>Full Name</label>
          <input type="text" name="name" class="form-control"
                 value="<?php echo htmlspecialchars($u['name']); ?>" required>
        </div>
        <div class="form-group">
          <label>Email Address <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--text-light)">(cannot change)</span></label>
          <input type="email" class="form-control" value="<?php echo htmlspecialchars($u['email']); ?>"
                 disabled style="opacity:.6;cursor:not-allowed">
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label>Phone Number</label>
          <input type="tel" name="phone" class="form-control"
                 value="<?php echo htmlspecialchars($u['phone'] ?? ''); ?>"
                 placeholder="08012345678">
        </div>
      </div>
    </div>

    <!-- Change Password -->
    <div class="card" style="margin-bottom:20px">
      <div class="card-header">
        <h3>Change Password</h3>
        <span style="font-size:.75rem;color:var(--text-muted)">Leave blank to keep current</span>
      </div>
      <div class="card-body">
        <div class="form-group">
          <label>Current Password</label>
          <div style="position:relative">
            <input type="password" id="pw1" name="current_password" class="form-control"
                   placeholder="Enter current password" style="padding-right:46px">
            <button type="button" onclick="togglePw('pw1')"
                    style="position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-muted)">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            </button>
          </div>
        </div>
        <div class="grid-2">
          <div class="form-group" style="margin-bottom:0">
            <label>New Password</label>
            <input type="password" id="pw2" name="new_password" class="form-control" placeholder="Min. 6 characters">
          </div>
          <div class="form-group" style="margin-bottom:0">
            <label>Confirm New Password</label>
            <input type="password" id="pw3" name="confirm_password" class="form-control" placeholder="Repeat">
          </div>
        </div>
      </div>
    </div>

    <button type="submit" class="btn btn-primary btn-lg btn-block">Save Changes</button>
  </form>
</div>

<script>
function togglePw(id) {
  const f = document.getElementById(id);
  f.type = f.type === 'password' ? 'text' : 'password';
}
</script>

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