<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

$host = "localhost";
$db = "togethere_cloud";
$user = "root";
$pass = "HasloDoSQL";

try {
    
$pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch (PDOException $e) {
    die("Błąd połączenia z bazą danych: " . $e->getMessage());
}

$email = $_GET['email'] ?? $_SESSION['pending_email'] ?? '';
$error = '';
$success = '';
$link_expired = false;

if (!empty($_SESSION['verify_success'])) {
    $success = $_SESSION['verify_success'];
    unset($_SESSION['verify_success']);
}

// SPRAWDZENIE CZY LINK NIE WYGASŁ - na samym początku przed jakimkolwiek action
if (!empty($email)) {
    $stmt = $pdo->prepare("SELECT id, username, verification_code, verification_expires, email_verified FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $check_user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($check_user && (int)$check_user['email_verified'] === 1) {
        unset($_SESSION['pending_user_id'], $_SESSION['pending_email']);
        header('Location: /login/?success=already_verified');
        exit();
    }
    
    if ($check_user && $check_user['email_verified'] != 1) {
        // Sprawdź czy kod wygasł
        if (strtotime($check_user['verification_expires']) < time()) {
            $link_expired = true;
        }
    }
}

// Obsługa wysłania kodu ponownie - TYLKO PRZEZ PRZYCISK (GET)
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['resend']) && $_GET['resend'] == '1' && !empty($email)) {
    $stmt = $pdo->prepare("SELECT id, username, email_verified FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user && $user['email_verified'] != 1) {
        // Generowanie nowego kodu
        $new_code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $new_expires = date('Y-m-d H:i:s', strtotime('+15 minutes'));
        
        $update = $pdo->prepare("UPDATE users SET verification_code = ?, verification_expires = ? WHERE id = ?");
        $update->execute([$new_code, $new_expires, $user['id']]);
        
        // Wysłanie nowego emaila
        require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/smtp_helper.php';
        
        $subject = "Nowy kod weryfikacyjny - Wspólnie";
        $message = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <style>
        body { font-family: 'Lato', Arial, sans-serif; background: #f0f8ff; padding: 20px; }
        .container { max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        h1 { color: #1976d2; text-align: center; }
        .code { font-size: 32px; font-weight: bold; color: #007BFF; text-align: center; letter-spacing: 5px; margin: 30px 0; padding: 20px; background: #e3f2fd; border-radius: 10px; }
        p { color: #2c3e50; line-height: 1.6; }
        .footer { margin-top: 30px; padding-top: 20px; border-top: 2px solid #e3f2fd; text-align: center; color: #7f8c8d; font-size: 14px; }
    </style>
</head>
<body>
    <div class='container'>
        <h1>🎮 Nowy kod weryfikacyjny</h1>
        <p>Twój nowy kod weryfikacyjny to:</p>
        <div class='code'>$new_code</div>
        <p>Kod jest ważny przez <strong>15 minut</strong>.</p>
        <div class='footer'>
            <p>&copy; 2026 Wspólnie. Wszelkie prawa zastrzeżone.</p>
        </div>
    </div>
</body>
</html>
        ";
        
        sendEmailSMTP($email, $subject, $message);
        $_SESSION['verify_success'] = "Nowy kod został wysłany na Twój email!";
        $link_expired = false; // Link jest teraz znowu aktywny po resend

        header('Location: /login/verify.php?email=' . urlencode($email));
        exit();
    }
}

if ($_SERVER["REQUEST_METHOD"] === "POST" && !$link_expired) {
    $code = trim($_POST["code"] ?? "");
    $email = trim($_POST["email"] ?? "");
    
    if (empty($code) || empty($email)) {
        $error = "Kod weryfikacyjny jest wymagany.";
    } else {
        $stmt = $pdo->prepare("SELECT id, username, verification_code, verification_expires, email_verified 
                               FROM users 
                               WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            $error = "Nie znaleziono użytkownika.";
        } elseif ($user['email_verified'] == 1) {
            header('Location: /login/?success=already_verified');
            exit();
        } else {
            // Sprawdzenie czy kod wygasł
            if (strtotime($user['verification_expires']) < time()) {
                $error = "Kod weryfikacyjny wygasł.";
                $link_expired = true;
            } elseif ($user['verification_code'] != $code) {
                // TYLKO BŁĄD - BRAK AUTOMATYCZNEGO WYSYŁANIA
                $error = "Nieprawidłowy kod weryfikacyjny.";
            } else {
                // Weryfikacja udana - aktywacja konta
                $update = $pdo->prepare("UPDATE users SET email_verified = 1, verification_code = NULL, verification_expires = NULL WHERE id = ?");
                $update->execute([$user['id']]);
                
                // Automatyczne logowanie po weryfikacji
                $_SESSION['logged_in'] = true;
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $email;
                
                // Usunięcie pending sesji
                unset($_SESSION['pending_user_id']);
                unset($_SESSION['pending_email']);
                
                header('Location: https://togethere.cloud/home/');
                exit();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Weryfikacja Email | Wspólnie</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <link rel="stylesheet" href="/css/header.css" type="text/css" media="all"/>
    <link rel="stylesheet" href="/css/footer.css" type="text/css" media="all"/>
    <link href="/css/font-awesome.min.css" rel="stylesheet" type="text/css" media="all">
    <link href="/css/style.css" rel="stylesheet" type="text/css" media="all"/>
    <link href="//fonts.googleapis.com/css?family=Lato:400,500,600,700,800,900" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .verify-container {
            max-width: 500px;
            margin: 80px auto;
            padding: 40px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(100, 181, 246, 0.2);
            flex: 1;
        }

        .verify-container * {
            box-sizing: border-box !important;
        }

        .verify-container form {
            width: 100% !important;
            max-width: 100% !important;
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
        }

        .verify-container form {
            width: 100% !important;
            max-width: 100% !important;
        }

        h1 {
            color: #1976d2;
            font-size: 2em;
            margin-bottom: 10px;
            text-align: center;
        }

        .subtitle {
            text-align: center;
            color: #7f8c8d;
            margin-bottom: 30px;
            font-size: 0.95em;
        }

        .form-group {
            margin-bottom: 25px !important;
            text-align: center !important;
            display: flex !important;
            justify-content: center !important;
        }

        input[type="text"] {
            width: 300px !important;
            max-width: 300px !important;
            padding: 15px !important;
            border: 2px solid #e3f2fd !important;
            border-radius: 8px !important;
            font-size: 24px !important;
            letter-spacing: 8px !important;
            text-align: center !important;
            font-weight: bold !important;
            color: #007BFF !important;
            transition: all 0.3s ease !important;
            margin: 0 auto !important;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #007BFF;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        button {
            width: 100% !important;
            max-width: 300px !important;
            padding: 15px !important;
            background: linear-gradient(135deg, #007BFF 0%, #0056b3 100%) !important;
            color: white !important;
            border: none !important;
            border-radius: 8px !important;
            font-size: 1.1em !important;
            font-weight: 600 !important;
            cursor: pointer !important;
            transition: all 0.3s ease !important;
            display: block !important;
            margin: 0 auto !important;
        }

        button:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3) !important;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%) !important;
            margin-top: 15px !important;
        }

        .success {
            background: #d4edda !important;
            color: #155724 !important;
            padding: 15px !important;
            border-radius: 8px !important;
            margin-bottom: 20px !important;
            text-align: center !important;
            border-left: 4px solid #28a745 !important;
        }

        .error {
            background: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            border-left: 4px solid #c62828;
        }

        .info-box {
            background: #e3f2fd;
            border-left: 4px solid #42a5f5;
            padding: 15px;
            margin-bottom: 25px;
            border-radius: 5px;
            font-size: 0.95em;
            color: #2c3e50;
        }

        .resend-link {
            text-align: center;
            margin-top: 20px;
            color: #7f8c8d;
            font-size: 0.9em;
        }

        .resend-link a {
            color: #007BFF;
            text-decoration: none;
            font-weight: 600;
        }

        .resend-link a:hover {
            text-decoration: underline;
        }

        @media (max-width: 768px) {
            .verify-container {
                margin: 40px 20px;
                padding: 30px 20px;
            }

            h1 {
                font-size: 1.5em;
            }

            input[type="text"] {
                font-size: 20px;
                letter-spacing: 5px;
            }
        }
    </style>
    <script>
        // Delay 60s na przycisk resend
        document.addEventListener('DOMContentLoaded', function() {
            const resendBtn = document.getElementById('resend-btn');
            if (!resendBtn) return;
            
            // Sprawdź czy był już kliknięty (localStorage)
            const lastResend = localStorage.getItem('lastResendTime');
            if (lastResend) {
                const elapsed = Math.floor((Date.now() - parseInt(lastResend)) / 1000);
                if (elapsed < 60) {
                    startCountdown(60 - elapsed);
                }
            }
            
            resendBtn.addEventListener('click', function(e) {
                if (resendBtn.disabled) {
                    e.preventDefault();
                    return;
                }
                localStorage.setItem('lastResendTime', Date.now());
            });
            
            function startCountdown(seconds) {
                resendBtn.disabled = true;
                resendBtn.style.opacity = '0.5';
                resendBtn.style.cursor = 'not-allowed';
                
                const originalText = resendBtn.textContent;
                
                const interval = setInterval(function() {
                    resendBtn.textContent = `Wysyłanie ponownie za ${seconds}s`;
                    seconds--;
                    
                    if (seconds < 0) {
                        clearInterval(interval);
                        resendBtn.disabled = false;
                        resendBtn.style.opacity = '1';
                        resendBtn.style.cursor = 'pointer';
                        resendBtn.textContent = originalText;
                        localStorage.removeItem('lastResendTime');
                    }
                }, 1000);
            }
            
            // Sprawdzanie, czy w URL jest resend=1
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('resend') === '1') {
                startCountdown(60);
            }
        });
    </script>
</head>
<body>
    <?php
        if (!empty($_SESSION['logged_in'])) {
            include __DIR__ . '/../global/navLogined.php';
        } else {
            include __DIR__ . '/../global/navNoLogined.php';
        }
    ?>

    <div class="verify-container">
        <h1>✉️ Weryfikacja Email</h1>
        <p class="subtitle">Wpisz 6-cyfrowy kod wysłany na Twój email</p>

        <?php if ($error): ?>
            <div class="error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <?php if ($link_expired): ?>
            <div class="error">
                <strong>⏰ Link weryfikacyjny wygasł!</strong><br>
                Twój kod weryfikacyjny stracił ważność po 15 minutach.<br>
                Kliknij przycisk poniżej aby otrzymać nowy kod.
            </div>
        <?php endif; ?>

        <div class="info-box">
            <strong>📧 Email:</strong> <?= htmlspecialchars($email) ?><br>
            <strong>⏱️ Kod ważny:</strong> 15 minut od wysłania
        </div>

        <?php if (!$link_expired): ?>
        <form method="POST" action="/login/verify.php?email=<?= urlencode($email) ?>">
            <input type="hidden" name="email" value="<?= htmlspecialchars($email) ?>">
            
            <div class="form-group">
                <input type="text" id="code" name="code" maxlength="6" pattern="[0-9]{6}" 
                       placeholder="000000" required autofocus>
            </div>

            <button type="submit">Zweryfikuj Email</button>
        </form>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; margin: 20px 0;">
                Formularz jest zablokowany. Kliknij "Wyślij kod ponownie" aby otrzymać nowy kod.
            </p>
        <?php endif; ?>

        <button type="button" id="resend-btn" class="btn-secondary" 
                onclick="if(!this.disabled) window.location.href='?email=<?= urlencode($email) ?>&resend=1'">
            Wyślij kod ponownie
        </button>

        <div class="resend-link">
            Nie otrzymałeś kodu? <a href="/login/">Zaloguj się ponownie</a>
        </div>
    </div>

    <?php
        if (!empty($_SESSION['logged_in'])) {
            include __DIR__ . '/../global/footerLogined.php';
        } else {
            include __DIR__ . '/../global/footerNoLogined.php';
        }
    ?>
</body>
</html>

