<?php
// security_process.php
require 'config/db.php';


// 1. Check if user is logged in
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$current_user_id = $_SESSION['user_id']; // Direct numeric ID

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_password'])) {
    
    $current_pass = $_POST['current_password'] ?? '';
    $new_pass     = $_POST['new_password'] ?? '';
    $confirm_pass = $_POST['confirm_password'] ?? '';

    try {
        // 2. Fetch the current hashed password from the Vault
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$current_user_id]);
        $user = $stmt->fetch();

        if (!$user) { die("System Error: Account not found."); }

        // 3. Validation Logic
        if (!password_verify($current_pass, $user['password'])) {
            die("Error: Current password is incorrect.");
        }

        if (strlen($new_pass) < 8) { // Upgraded to 8 for better security
            die("Error: New password is too weak. Minimum 8 characters required.");
        }

        if ($new_pass !== $confirm_pass) {
            die("Error: New passwords do not match.");
        }

        // 4. Hash and Update
        $hashed_pass = password_hash($new_pass, PASSWORD_DEFAULT);
        
        $update_stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        if ($update_stmt->execute([$hashed_pass, $current_user_id])) {
            // Success redirect
            header("Location: dashboard.php?success=password_updated");
            exit;
        }

    } catch (PDOException $e) {
        error_log("Password Update Error: " . $e->getMessage());
        die("Critical Vault Error. Please contact support.");
    }
}