<?php
// confirm_reset.php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require 'db_connect.php'; // Make sure this path is correct

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database connection failed.';
    echo json_encode($response);
    exit;
}

// 1. Get data from the POST request
$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';

if (empty($mobile) || empty($code) || empty($new_password)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Missing required fields.';
    echo json_encode($response);
    exit;
}

// 2. **CRITICAL FIX**: Normalize the mobile number exactly as you did before
$normalized_mobile = substr($mobile, -10);

try {
    // 3. Find the user with BOTH the mobile number AND the reset code
    $sql_check = "SELECT id FROM users WHERE mobile LIKE CONCAT('%', ?) AND reset_code = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("ss", $normalized_mobile, $code);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        $user = $result_check->fetch_assoc();

        // 4. Hash the new password for security
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        // 5. Update the password and clear the reset code
        $sql_update = "UPDATE users SET password = ?, reset_code = NULL WHERE id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("si", $hashed_password, $user['id']);
        $stmt_update->execute();
        $stmt_update->close();

        $response['status'] = 'success';
        $response['message'] = 'Password has been reset successfully.';
        echo json_encode($response);

    } else {
        // This is where the "Invalid reset code" message comes from
        http_response_code(400);
        $response['status'] = 'error';
        $response['message'] = 'Invalid reset code.';
        echo json_encode($response);
    }
    $stmt_check->close();

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'An internal server error occurred.';
    error_log("Password Reset Error: " . $e->getMessage()); // Log the actual error
    echo json_encode($response);
}

$conn->close();
exit;
?>