<?php
session_start();
require_once 'db/config.php';
require_once 'includes/auth_helpers.php';

// Protect route: check if user is logged in
if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_new_password = $_POST['confirm_new_password'] ?? '';

    // 1. Validate inputs
    if (empty($current_password) || empty($new_password) || empty($confirm_new_password)) {
        $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'All fields are required.'];
        header('Location: profile.php');
        exit();
    }

    if ($new_password !== $confirm_new_password) {
        $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'New passwords do not match.'];
        header('Location: profile.php');
        exit();
    }

    try {
        $pdo = db();
        
        // 2. Fetch current user from DB to verify current password
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user']['id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user || !password_verify($current_password, $user['password'])) {
            $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Incorrect current password.'];
            header('Location: profile.php');
            exit();
        }

        // 3. Hash new password
        $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);

        // 4. Update password in the database
        $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->execute([$new_password_hash, $_SESSION['user']['id']]);

        $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Password updated successfully.'];
        header('Location: profile.php');
        exit();

    } catch (PDOException $e) {
        // Log error and show a generic message
        error_log("Password update failed: " . $e->getMessage());
        $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'An error occurred. Please try again.'];
        header('Location: profile.php');
        exit();
    }

} else {
    // Redirect if not a POST request
    header('Location: profile.php');
    exit();
}
