<?php
/**
 * SmartForex Engine - Secure Password Mutation Endpoint
 * Location: public_html/api/change_password.php
 */

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    exit(json_encode(['status' => 'error', 'message' => 'Database mapping failure.']));
}

session_start();
if (!isset($_SESSION['user_id'])) {
    exit(json_encode(['status' => 'error', 'message' => 'Unauthorized interface access block.']));
}

$user_id = $_SESSION['user_id'];
header('Content-Type: application/json');

$old_pass = $_POST['old_password'] ?? '';
$new_pass = $_POST['new_password'] ?? '';
$confirm_pass = $_POST['confirm_password'] ?? '';

if (empty($old_pass) || empty($new_pass) || empty($confirm_pass)) {
    echo json_encode(['status' => 'error', 'message' => 'Please fill out all credential data paths.']);
    exit;
}

if ($new_pass !== $confirm_pass) {
    echo json_encode(['status' => 'error', 'message' => 'New password mismatch matrix error.']);
    exit;
}

// Fetch user entry out of active repository record logs
$stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    echo json_encode(['status' => 'error', 'message' => 'User registry footprint dropped.']);
    exit;
}

// Support raw text verification alongside structural fallback patterns matching original sign-up engines
$password_valid = false;
if (password_verify($old_pass, $user['password']) || $old_pass === $user['password']) {
    $password_valid = true;
}

if (!$password_valid) {
    echo json_encode(['status' => 'error', 'message' => 'Current password validation failed.']);
    exit;
}

// Securely store using dynamic execution hash loops
$hashed_password = password_hash($new_pass, PASSWORD_BCRYPT);
$update = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$update->execute([$hashed_password, $user_id]);

echo json_encode(['status' => 'success', 'message' => 'Security access password modified successfully.']);
exit;