<?php
ob_start();
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
require '../config/conn.php';
require '../vendor/autoload.php';

// Rate limiting - max 5 attempts in 15 minutes
if (!isset($_SESSION['admin_verify_attempts'])) {
    $_SESSION['admin_verify_attempts'] = 0;
    $_SESSION['admin_first_attempt_time'] = time();
}

if ($_SESSION['admin_verify_attempts'] >= 5 && 
    (time() - $_SESSION['admin_first_attempt_time']) < 900) {
    die("Too many attempts. Please try again later.");
}

if (!isset($_SESSION['admin_2fa_id'])) {
    header("Location: admin-login.php");
    exit();
}

$error = '';
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify code submission
    if (isset($_POST['verify'])) {
        $code = trim($_POST['code'] ?? '');
        
        if (empty($code)) {
            $error = "Verification code is required";
        } elseif (!preg_match('/^\d{6}$/', $code)) {
            $error = "Invalid code format. Please enter a 6-digit number.";
        } else {
            // Modified query to match your actual table structure
            $stmt = $conn->prepare("SELECT vc.*, a.* 
                                   FROM admin_verification_codes vc
                                   JOIN admins a ON vc.admin_id = a.id
                                   WHERE vc.admin_id = ? 
                                   AND vc.code = ? 
                                   AND vc.expires_at > NOW()
                                   ORDER BY vc.created_at DESC 
                                   LIMIT 1");
            $stmt->bind_param("is", $_SESSION['admin_2fa_id'], $code);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 1) {
                $row = $result->fetch_assoc();
                
                // Mark code as used (if you have this column)
                // First check if the column exists or modify your table
                $update_stmt = $conn->prepare("UPDATE admin_verification_codes 
                                             SET is_used = 1 
                                             WHERE id = ?");
                $update_stmt->bind_param("i", $row['id']);
                
                if ($update_stmt->execute()) {
                    // Regenerate session ID
                    session_regenerate_id(true);
                    
                    // Set session variables
                    $_SESSION['admin_id'] = $row['id'];
                    $_SESSION['admin_username'] = $row['full_name'];
                    $_SESSION['admin_email'] = $row['email'];
                    $_SESSION['admin_role'] = $row['role'];
                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_last_activity'] = time();

                    // Remember me functionality
                    if (isset($_SESSION['admin_2fa_remember_me']) && $_SESSION['admin_2fa_remember_me']) {
                        $token = bin2hex(random_bytes(32));
                        $expiry = date('Y-m-d H:i:s', strtotime('+30 days'));
                        
                        $stmt = $conn->prepare("INSERT INTO admin_remember_tokens 
                                              (admin_id, token, expires_at) 
                                              VALUES (?, ?, ?)");
                        $stmt->bind_param("iss", $row['id'], $token, $expiry);
                        $stmt->execute();
                        
                        setcookie('admin_remember_token', $token, [
                            'expires' => time() + (30 * 24 * 60 * 60),
                            'path' => '/admin',
                            'secure' => true,
                            'httponly' => true,
                            'samesite' => 'Strict'
                        ]);
                    }

                    // Record login history
                    $ip_address = $_SERVER['REMOTE_ADDR'];
                    $device_info = $_SERVER['HTTP_USER_AGENT'];
                    
                    $login_stmt = $conn->prepare("INSERT INTO admin_login_history 
                                                (admin_id, ip_address, device_info) 
                                                VALUES (?, ?, ?)");
                    $login_stmt->bind_param("iss", $row['id'], $ip_address, $device_info);
                    $login_stmt->execute();
                    
                    // Update last login
                    $update_stmt = $conn->prepare("UPDATE admins 
                                                 SET last_login = NOW() 
                                                 WHERE id = ?");
                    $update_stmt->bind_param("i", $row['id']);
                    $update_stmt->execute();

                    // Clear 2FA session
                    unset($_SESSION['admin_2fa_id']);
                    unset($_SESSION['admin_2fa_remember_me']);
                    unset($_SESSION['admin_verify_attempts']);
                    
                    // Ensure no output before header
                    ob_end_clean();
                    header("Location:index.php");
                    exit();
                } else {
                    $error = "System error during verification. Please try again.";
                }
            } else {
                $_SESSION['admin_verify_attempts']++;
                $error = "Invalid verification code or code has expired";
            }
        }
    }
    
    // Resend code functionality
    if (isset($_POST['resend'])) {
        // Generate a new 6-digit verification code
        $verification_code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        
        // Store the new code in the database
        $stmt = $conn->prepare("INSERT INTO admin_verification_codes 
                              (admin_id, code, expires_at, ip_address) 
                              VALUES (?, ?, ?, ?)");
        $stmt->bind_param("isss", $_SESSION['admin_2fa_id'], $verification_code, $expires_at, $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        
        // Get admin details
        $user_stmt = $conn->prepare("SELECT username, email FROM admins WHERE id = ?");
        $user_stmt->bind_param("i", $_SESSION['admin_2fa_id']);
        $user_stmt->execute();
        $user_result = $user_stmt->get_result();
        $admin = $user_result->fetch_assoc();
        
        // Send the new verification code via email
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'your-email@gmail.com';
            $mail->Password   = 'your-app-password';
            $mail->SMTPSecure = PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;
            
            // Recipients
            $mail->setFrom('noreply@yourdomain.com', 'Your System Name');
            $mail->addAddress($admin['email'], $admin['username']);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Your New Admin Login Verification Code';
            
            $mail->Body = "
            <div style='max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden;'>
                <div style='background-color: #FBBB01; padding: 25px; text-align: center;'>
                    <h1 style='color: white; margin: 0; font-size: 24px;'>New Admin Verification Code</h1>
                </div>
                
                <div style='padding: 25px;'>
                    <h2 style='color: #FBBB01; margin-top: 0;'>Hello Admin {$admin['username']},</h2>
                    
                    <p style='font-size: 16px;'>Your new admin login verification code is:</p>
                    
                    <div style='text-align: center; margin: 25px 0;'>
                        <div style='display: inline-block; padding: 15px 30px; background-color: #f5f5f5; border: 2px dashed #FBBB01; border-radius: 5px; font-size: 24px; font-weight: bold; letter-spacing: 5px;'>
                            $verification_code
                        </div>
                    </div>
                    
                    <p style='font-size: 14px; color: #666;'>This code will expire in 10 minutes. Please do not share this code with anyone.</p>
                </div>
                
                <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666;'>
                    <p>© " . date('Y') . " Your System Name. All rights reserved.</p>
                </div>
            </div>
            ";
            
            $mail->AltBody = "Hello Admin {$admin['username']},\n\n"
                . "Your new admin login verification code is: $verification_code\n\n"
                . "This code will expire in 10 minutes. Please do not share this code with anyone.\n\n"
                . "Best regards,\n"
                . "Your System Name";
            
            $mail->send();
            
            $_SESSION['admin_last_code_sent'] = time();
            $success = "A new verification code has been sent to your admin email.";
        } catch (Exception $e) {
            $error = "Failed to send new verification code. Please try again later.";
        }
        
        // Redirect to avoid form resubmission
        header("Location: admin-verify-code.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Verification | Your System Name</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .btn-primary {
            background-color: #fbbb01;
        }
        .btn-primary:hover {
            background-color: #e0a800;
        }
        .input-focus:focus {
            border-color: #fbbb01;
            ring-color: #fbbb01;
        }
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f8f9fa;
        }
        .admin-verify-container {
            max-width: 28rem;
            margin: 2rem auto;
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            padding: 2rem;
        }
        .admin-header {
            text-align: center;
            margin-bottom: 1.5rem;
        }
        .admin-header h1 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #1a202c;
        }
        .admin-header p {
            color: #4a5568;
            margin-top: 0.5rem;
        }
        .admin-logo {
            width: 3rem;
            height: 3rem;
            margin: 0 auto 1rem;
            background-color: #fbbb01;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-5">
    <div class="admin-verify-container">
        <div class="admin-header">
            <div class="admin-logo">
                <i class="fas fa-lock"></i>
            </div>
            <h1>Admin Verification</h1>
            <p>Enter the 6-digit code sent to your admin email</p>
        </div>
        
        <?php if ($error): ?>
            <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6 text-red-700">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg mb-6 text-green-700">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>
        
        <form method="POST" action="admin-verify-code.php">
            <div class="mb-6">
                <label for="code" class="block text-gray-700 font-medium mb-2">Verification Code</label>
                <div class="relative">
                    <input type="text" id="code" name="code" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#fbbb01] focus:border-[#fbbb01] input-focus"
                           maxlength="6" pattern="\d{6}" title="Please enter a 6-digit code" required autofocus
                           placeholder="••••••">
                    <div class="absolute right-3 top-3 text-gray-400">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                </div>
                <small class="text-gray-500 text-sm mt-1 block">Check your admin email for the verification code</small>
            </div>
            
            <button type="submit" name="verify" class="w-full py-3 px-4 bg-[#fbbb01] text-white font-medium rounded-lg hover:bg-[#e0a800] transition duration-200 mb-4">
                <i class="fas fa-sign-in-alt mr-2"></i> Verify & Continue
            </button>
            
            <div class="text-center text-sm text-gray-600 pt-4 border-t border-gray-200">
                <p>Didn't receive a code? 
                    <button type="submit" name="resend" class="text-[#fbbb01] hover:text-[#e0a800] hover:underline focus:outline-none">
                        <i class="fas fa-redo mr-1"></i> Resend Code
                    </button>
                </p>
                <p class="mt-2">
                    <a href="admin-login.php" class="text-[#fbbb01] hover:text-[#e0a800] hover:underline">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Login
                    </a>
                </p>
            </div>
        </form>
    </div>
    
    
       
    <script>
    // This script helps with better UX for code input without auto-submitting
    document.getElementById('code').addEventListener('input', function(e) {
        // Just ensure the input is numeric and max 6 digits
        this.value = this.value.replace(/[^0-9]/g, '').substring(0, 6);
    });
    </script>

</body>
</html>