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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $current = $_POST['current_password'];
    $new = $_POST['new_password'];
    $confirm = $_POST['confirm_password'];

    if (!password_verify($current, $user['password'])) {
        echo "Current password incorrect.";
    } elseif ($new !== $confirm) {
        echo "New passwords do not match.";
    } else {
        $hashed = password_hash($new, PASSWORD_BCRYPT);
        $conn->query("UPDATE users SET password='$hashed' WHERE id=$user_id");

        // Email alert
        mail($user['email'], "Password Changed - Pharma Research", "Your account password was changed successfully.");

        echo "Password updated successfully.";
    }
}
?>
<html>
    <head>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    </head>
<body>
<h2>Privacy & Security</h2>
<div class="container mt-5">
  <div class="card shadow-lg p-4 rounded-4 col-md-6 mx-auto">
    <h2 class="text-danger mb-4 text-center">Change Password</h2>
    <form method="POST" class="row g-3">
      <div class="col-12">
        <label class="form-label">Current Password</label>
        <input type="password" name="current_password" class="form-control" required>
      </div>
      <div class="col-12">
        <label class="form-label">New Password</label>
        <input type="password" name="new_password" minlength="6" class="form-control" required>
      </div>
      <div class="col-12">
        <label class="form-label">Confirm New Password</label>
        <input type="password" name="confirm_password" minlength="6" class="form-control" required>
      </div>
      <div class="col-12 text-center">
        <button type="submit" class="btn btn-danger px-5">Update Password</button>
      </div>
    </form>
  </div>
</div>

<button onclick="window.location.href='dashboard.php'">Back to Dashboard</button>

</body>
</html>