<?php
include("../config.php");
include("edFunction.php"); 
header('Content-Type: application/json');

$postData = json_decode(file_get_contents('php://input'), true);

if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Validate incoming data
if (!isset($postData['validationCode']) || empty($postData['validationCode'])) {
    echo json_encode(['status' => 'error', 'message' => 'Email is required']);
    exit;
}
if (!isset($postData['password']) || empty($postData['password'])) {
    echo json_encode(['status' => 'error', 'message' => 'Password is required']);
    exit;
}

$email = decryptData($postData['validationCode']);
$password = password_hash($postData['password'], PASSWORD_BCRYPT); // Secure password hashing

// Check if email exists
$checkEmailQuery = "SELECT id FROM users WHERE email = '$email'";
$result = mysqli_query($db, $checkEmailQuery);

if ($result && mysqli_num_rows($result) > 0) {
    // If email exists, update the password
    $updateQuery = "UPDATE users SET password = '$password' WHERE email = '$email'";
    if (mysqli_query($db, $updateQuery)) {
        echo json_encode(['status' => 'success', 'message' => 'Password updated successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to update password', 'error' => mysqli_error($db)]);
    }
}
?>
