<?php
session_start();
require_once "../includes/db.php";

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

$user_id = $_SESSION['user_id'];

$current_password = $_POST['current_password'] ?? '';
$new_password     = $_POST['new_password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

if ($new_password !== $confirm_password) {
    header("Location: ../users/change_password?error=New password confirmation does not match");
    exit;
}

$stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($current_password, $user['password'])) {
    header("Location: ../users/change_password?error=The current password you entered is incorrect");
    exit;
}

$newPasswordHash = password_hash($new_password, PASSWORD_DEFAULT);

$stmt = $pdo->prepare("UPDATE users SET password = ?, pshow = ? WHERE id = ?");
$stmt->execute([$newPasswordHash, $confirm_password, $user_id]);

header("Location: ../users/change_password?success=Your password has been updated successfully");
exit;
