<?php
// Real-time verification API
// Handles all real-time verification checks during registration/login

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

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/EmailService.php';

$action = $_GET['action'] ?? '';
$response = array('status' => 'error', 'message' => '');

try {
    switch ($action) {
        // Check if email exists (real-time during registration)
        case 'check_email':
            $email = trim($_GET['email'] ?? '');
            
            if (!$email) {
                $response['message'] = 'Email is required';
                break;
            }
            
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $response['message'] = 'Invalid email format';
                break;
            }
            
            $stmt = $conn->prepare('SELECT id FROM users WHERE email = ?');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $response['status'] = 'error';
                $response['message'] = 'Email already registered';
                $response['available'] = false;
            } else {
                $response['status'] = 'success';
                $response['message'] = 'Email is available';
                $response['available'] = true;
            }
            $stmt->close();
            break;

        // Validate password strength (real-time)
        case 'check_password':
            $password = $_GET['password'] ?? '';
            $strength = 0;
            $feedback = array();
            
            if (strlen($password) >= 8) $strength++;
            else $feedback[] = 'At least 8 characters';
            
            if (preg_match('/[A-Z]/', $password)) $strength++;
            else $feedback[] = 'At least one uppercase letter';
            
            if (preg_match('/[a-z]/', $password)) $strength++;
            else $feedback[] = 'At least one lowercase letter';
            
            if (preg_match('/[0-9]/', $password)) $strength++;
            else $feedback[] = 'At least one number';
            
            if (preg_match('/[!@#$%^&*]/', $password)) $strength++;
            else $feedback[] = 'At least one special character (!@#$%^&*)';
            
            $strength_text = '';
            if ($strength <= 2) $strength_text = 'Weak';
            elseif ($strength <= 3) $strength_text = 'Fair';
            elseif ($strength <= 4) $strength_text = 'Good';
            else $strength_text = 'Strong';
            
            $response['status'] = 'success';
            $response['strength'] = $strength;
            $response['strength_text'] = $strength_text;
            $response['feedback'] = $feedback;
            $response['valid'] = $strength >= 3;
            break;

        // Check password match (real-time)
        case 'check_password_match':
            $password = $_GET['password'] ?? '';
            $confirm = $_GET['confirm'] ?? '';
            
            $response['status'] = 'success';
            $response['match'] = $password === $confirm && $password !== '';
            $response['message'] = $response['match'] ? 'Passwords match' : 'Passwords do not match';
            break;

        // Validate phone number (real-time)
        case 'check_phone':
            $phone = preg_replace('/[^0-9]/', '', $_GET['phone'] ?? '');
            
            if (strlen($phone) < 10) {
                $response['status'] = 'error';
                $response['message'] = 'Phone must be at least 10 digits';
                $response['valid'] = false;
            } else {
                $response['status'] = 'success';
                $response['message'] = 'Phone number is valid';
                $response['valid'] = true;
                $response['formatted'] = $phone;
            }
            break;

        // Send OTP (real-time)
        case 'send_otp':
            $email = trim($_GET['email'] ?? '');
            $name = trim($_GET['name'] ?? '');
            
            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $response['message'] = 'Invalid email';
                break;
            }
            
            if (!$name) {
                $response['message'] = 'Name is required';
                break;
            }
            
            $email_service = new EmailService();
            $otp = $email_service->generateOTP(6);
            $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));
            $purpose = 'email_verification';
            
            // Clear old OTPs for this email
            $delete_stmt = $conn->prepare('DELETE FROM otp_verification WHERE email = ? AND purpose = ?');
            $delete_stmt->bind_param('ss', $email, $purpose);
            $delete_stmt->execute();
            $delete_stmt->close();
            
            // Save new OTP
            $otp_stmt = $conn->prepare('INSERT INTO otp_verification (email, otp_code, purpose, expires_at) VALUES (?, ?, ?, ?)');
            $otp_stmt->bind_param('ssss', $email, $otp, $purpose, $expires);
            
            if ($otp_stmt->execute()) {
                if ($email_service->sendEmailVerificationOTP($email, $name, $otp)) {
                    $response['status'] = 'success';
                    $response['message'] = 'OTP sent to your email';
                    $response['otp_sent'] = true;
                } else {
                    $response['message'] = 'Failed to send OTP';
                }
            } else {
                $response['message'] = 'Error generating OTP';
            }
            $otp_stmt->close();
            break;

        // Verify OTP in real-time
        case 'verify_otp':
            $email = $_GET['email'] ?? '';
            $otp = $_GET['otp'] ?? '';
            
            if (!$email || !$otp) {
                $response['message'] = 'Email and OTP required';
                break;
            }
            
            $otp_stmt = $conn->prepare('SELECT id FROM otp_verification WHERE email = ? AND otp_code = ? AND purpose = ? AND expires_at > NOW()');
            $purpose = 'email_verification';
            $otp_stmt->bind_param('sss', $email, $otp, $purpose);
            $otp_stmt->execute();
            $otp_result = $otp_stmt->get_result();
            
            if ($otp_result->num_rows > 0) {
                $response['status'] = 'success';
                $response['message'] = 'OTP verified successfully';
                $response['verified'] = true;
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Invalid or expired OTP';
                $response['verified'] = false;
            }
            $otp_stmt->close();
            break;

        // Check email for login (real-time)
        case 'check_login_email':
            $email = trim($_GET['email'] ?? '');
            $role = trim($_GET['role'] ?? 'customer');
            
            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $response['message'] = 'Invalid email';
                break;
            }
            
            $stmt = $conn->prepare('SELECT id, role FROM users WHERE email = ?');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                if ($row['role'] === $role) {
                    $response['status'] = 'success';
                    $response['message'] = 'Email found';
                    $response['exists'] = true;
                } else {
                    $response['status'] = 'error';
                    $response['message'] = 'This email is not registered as ' . $role;
                    $response['exists'] = false;
                }
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Email not registered';
                $response['exists'] = false;
            }
            $stmt->close();
            break;

        // Get OTP expiration time (real-time)
        case 'check_otp_expiry':
            $email = trim($_GET['email'] ?? '');
            
            if (!$email) {
                $response['message'] = 'Email required';
                break;
            }
            
            $stmt = $conn->prepare('SELECT expires_at FROM otp_verification WHERE email = ? ORDER BY created_at DESC LIMIT 1');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $expiry = strtotime($row['expires_at']);
                $now = time();
                $remaining = $expiry - $now;
                
                if ($remaining > 0) {
                    $response['status'] = 'success';
                    $response['expires_at'] = $row['expires_at'];
                    $response['remaining_seconds'] = $remaining;
                    $response['remaining_minutes'] = ceil($remaining / 60);
                    $response['expired'] = false;
                } else {
                    $response['status'] = 'error';
                    $response['message'] = 'OTP has expired';
                    $response['expired'] = true;
                }
            } else {
                $response['status'] = 'error';
                $response['message'] = 'No OTP found';
            }
            $stmt->close();
            break;

        // Check 2FA requirement (real-time)
        case 'check_2fa':
            $email = trim($_GET['email'] ?? '');
            
            if (!$email) {
                $response['message'] = 'Email required';
                break;
            }
            
            $stmt = $conn->prepare('SELECT two_factor_enabled FROM users WHERE email = ?');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $response['status'] = 'success';
                $response['two_factor_enabled'] = $row['two_factor_enabled'] == 1;
                $response['message'] = $response['two_factor_enabled'] ? '2FA is enabled' : '2FA is not enabled';
            } else {
                $response['status'] = 'error';
                $response['message'] = 'User not found';
            }
            $stmt->close();
            break;

        default:
            $response['message'] = 'Invalid action: ' . htmlspecialchars($action);
    }
} catch (Exception $e) {
    $response['status'] = 'error';
    $response['message'] = 'Server error: ' . $e->getMessage();
}

echo json_encode($response);
?>
