<?php
include_once('../../includes/db.php');
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 'phone' and 'new_password' come from Flutter
    $input = sanitize($_POST['phone']);
    $new_password = sanitize($_POST['new_password']);
    
    // Normalize the phone number: Remove all non-digits
    $normalizedPhone = preg_replace('/\D/', '', $input);
    // Ensure the country code is present (Bahrain: 973)
    if (substr($normalizedPhone, 0, 3) !== '973') {
        $normalizedPhone = '973' . $normalizedPhone;
    }
    
    // Query using the same normalization technique as for OTP handling
    $user = fetchOne("
        SELECT * FROM users 
        WHERE REPLACE(REPLACE(REPLACE(phone, '+', ''), ' ', ''), '-', '') = ?
    ", [$normalizedPhone]);
    
    // Check user validity
    if (!$user || !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => false, 'message' => '❌ No user found with this phone or invalid email']);
        exit;
    }
    
    $email = $user['email'];
    $hashed = password_hash($new_password, PASSWORD_DEFAULT);
    
    // Update password using email as unique identifier
    $update = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
    $update->bind_param("ss", $hashed, $email);

    if ($update->execute()) {
        echo json_encode(['status' => true, 'message' => '✅ Password reset successful']);
    } else {
        echo json_encode(['status' => false, 'message' => '❌ Failed to reset password']);
    }
}
?>
