<?php
session_start();
include 'db.php';

if (!isset($_SESSION['user_id'])) {
    die("Access denied");
}

$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $old = $_POST['old_password'];
    $new = $_POST['new_password'];
    $confirm = $_POST['confirm_password'];
    $userId = $_SESSION['user_id'];

    if ($new !== $confirm) {
        $message = "❌ رمز جدید و تکرار آن یکسان نیست";
    } elseif (strlen($new) < 3) {
        $message = "❌ رمز عبور خیلی کوتاه است";
    } else {

        // Get old password from DB (PLAIN)
        $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows !== 1) {
            $message = "❌ کاربر یافت نشد";
        } else {
            $row = $res->fetch_assoc();

            // PLAIN TEXT CHECK
            if ($row['password'] === $old) {

                // UPDATE AS PLAIN TEXT
                $update = $conn->prepare("UPDATE users SET password=? WHERE id=?");
                $update->bind_param("si", $new, $userId);
                $update->execute();

                $message = "✅ رمز عبور با موفقیت تغییر یافت";
            } else {
                $message = "❌ رمز عبور فعلی اشتباه است";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<title>تغییر رمز عبور</title>
<style>
body {
  font-family: Tahoma, sans-serif;
  background: #eef2f7;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  direction: rtl;
  margin: 0;
}
.box {
  background: #fff;
  width: 330px;
  padding: 30px;
  border-radius: 14px;
  box-shadow: 0 8px 20px rgba(0,0,0,.15);
}
.box h2 {
  margin-bottom: 20px;
  text-align: center;
}
input {
  width: 100%;
  padding: 11px;
  margin: 8px 0;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 14px;
}
button {
  width: 100%;
  padding: 11px;
  background: #27ae60;
  border: none;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
}
button:hover {
  background: #219150;
}
.msg {
  margin-top: 15px;
  text-align: center;
  font-weight: bold;
}
</style>
</head>

<body>

<div class="box">
  <h2>تغییر رمز عبور</h2>

  <form method="post">
    <input type="password" name="old_password" placeholder="رمز عبور فعلی" required>
    <input type="password" name="new_password" placeholder="رمز عبور جدید" required>
    <input type="password" name="confirm_password" placeholder="تکرار رمز عبور جدید" required>
    <button type="submit">ذخیره</button>
  </form>

  <?php if ($message): ?>
    <div class="msg"><?= $message ?></div>
  <?php endif; ?>
</div>

</body>
</html>
