<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ]);
    exit;
}

// Get raw JSON input
$input = json_decode(file_get_contents('php://input'), true);

$email = isset($input['email']) ? trim($input['email']) : '';
$new_password = isset($input['new_password']) ? $input['new_password'] : '';

if (empty($email) || empty($new_password)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Email and new password are required.'
    ]);
    exit;
}

require '../database.php'; // Your DB connection

// Check if user exists
$sqlCheck = "SELECT * FROM users WHERE email = :email LIMIT 1";
$stmtCheck = $conn->prepare($sqlCheck);
$stmtCheck->bindParam(':email', $email);
$stmtCheck->execute();

$user = $stmtCheck->fetch(PDO::FETCH_ASSOC);

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

// Hash the new password
$hashedPassword = password_hash($new_password, PASSWORD_DEFAULT);

// Update password in DB
$sqlUpdate = "UPDATE users SET password = :password WHERE email = :email";
$stmtUpdate = $conn->prepare($sqlUpdate);
$stmtUpdate->bindParam(':password', $hashedPassword);
$stmtUpdate->bindParam(':email', $email);

if ($stmtUpdate->execute()) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Password updated successfully.'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to update password.'
    ]);
}
?>
