<?php
// header('Content-Type: application/json');
// header('Access-Control-Allow-Origin: *');
// header('Access-Control-Allow-Methods: POST');
// header('Access-Control-Allow-Headers: Content-Type');

// Include your existing connection file
require_once 'conn.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to generate random 6-digit OTP
function generateOTP() {
    return str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
}

// Function to send email
function sendVerificationEmail($email, $otp) {
    $subject = "Speedbitplus - Password Reset Verification Code";
    
    $message = "
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }
            .container { max-width: 600px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            .header { background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); color: white; padding: 20px; text-align: center; border-radius: 8px; }
            .otp-code { font-size: 32px; font-weight: bold; color: #f7921a; text-align: center; margin: 30px 0; letter-spacing: 5px; }
            .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666; font-size: 12px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Speedbitplus</h1>
                <h2>Password Reset Verification</h2>
            </div>
            
            <p>Hello,</p>
            
            <p>You requested a password reset for your Speedbitplus account. Use the verification code below to proceed:</p>
            
            <div class='otp-code'>$otp</div>
            
            <p>This code will expire in 10 minutes for security reasons.</p>
            
            <p>If you didn't request this reset, please ignore this email or contact our support team if you have concerns.</p>
            
            <div class='footer'>
                <p>Best regards,<br>The Speedbitplus Team</p>
                <p>© " . date('Y') . " Speedbitplus. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    // Use basic mail function (you can upgrade to PHPMailer if needed)
    return sendEmailBasic($email, $subject, $message);
}

// Basic mail function
function sendEmailBasic($email, $subject, $message) {
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: Speedbitplus <noreply@speedbitplus.com>" . "\r\n";
    
    return mail($email, $subject, $message, $headers);
}

// Main request handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['email']) || empty($input['email'])) {
            throw new Exception('Email is required');
        }
        
        $email = filter_var($input['email'], FILTER_SANITIZE_EMAIL);
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Invalid email format');
        }
        
        // Generate OTP
        $otp = generateOTP();
        $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        
   
        $check_user_sql = "SELECT id FROM users WHERE email = '$email'";
        $user_result = $conn->query($check_user_sql);
        
        if (!$user_result || $user_result->num_rows === 0) {
            throw new Exception('Email not found in our system');
        }
        
        // Check if record already exists in info table for this email
        $check_sql = "SELECT * FROM info WHERE email = '$email'";
        $check_result = $conn->query($check_sql);
        
        if ($check_result && $check_result->num_rows > 0) {
            // Update existing record
            $update_sql = "UPDATE info SET 
                          otp = '$otp', 
                          WHERE email = '$email'";
        } else {
            echo 'email does not exist ';
        }
        
        // Execute the query
        if (!$conn->query($update_sql)) {
            throw new Exception('Failed to store verification code: ' . $conn->error);
        }
        
        // Send email
        if (sendVerificationEmail($email, $otp)) {
            echo json_encode([
                'success' => true,
                'message' => 'Verification code sent to your email',
                'debug_otp' => $otp // Remove this in production
            ]);
        } else {
            throw new Exception('Failed to send verification email');
        }
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
}


?>