<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/security.php';

$redirect = isset($_GET['redirect']) ? $_GET['redirect'] : 'index.php';

if (isReseller()) {
    header('Location: ' . $redirect);
    exit;
}

$error = '';
$csrfToken = generateCSRFToken();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check honeypot
    if (isHoneypotFilled()) {
        logSecurityEvent('honeypot', 'Bot detected on login');
        $error = 'Bot detected.';
    }
    // Rate limit: 5 attempts per 15 minutes
    elseif (!checkRateLimit('cure_login_' . SITE_KEY . '_' . ($_SERVER['REMOTE_ADDR'] ?? ''), 5, 900)) {
        logSecurityEvent('rate_limit', 'Login rate limit exceeded', ['site' => SITE_KEY]);
        $error = 'Too many login attempts. Please wait 15 minutes.';
    }
    elseif (!isset($_POST['csrf_token']) || !validateCSRFToken($_POST['csrf_token'])) {
        $error = 'Invalid request. Please try again.';
    } else {
        $username = sanitizeString($_POST['username'] ?? '', 100);
        $password = $_POST['password'] ?? '';
        
        if (empty($username) || empty($password)) {
            $error = 'Please enter both username and password.';
        } else {
            $pdo = getDBConnection();
            $authenticated = false;
            
            if ($pdo) {
                try {
                    $stmt = $pdo->prepare("SELECT * FROM resellers WHERE (username = ? OR email = ?) AND active = 1");
                    $stmt->execute([$username, $username]);
                    $reseller = $stmt->fetch();
                    
                    if ($reseller && password_verify($password, $reseller['password'])) {
                        $_SESSION['reseller_logged_in'] = true;
                        $_SESSION['reseller_id'] = $reseller['id'];
                        $_SESSION['reseller_name'] = $reseller['name'];
                        $_SESSION['reseller_company'] = $reseller['company'];
                        $_SESSION['reseller_discount'] = $reseller['discount_percentage'];
                        $authenticated = true;
                        
                        $updateStmt = $pdo->prepare("UPDATE resellers SET last_login = NOW() WHERE id = ?");
                        $updateStmt->execute([$reseller['id']]);
                        
                        header('Location: ' . $redirect);
                        exit;
                    }
                } catch (PDOException $e) {
                    error_log("Login error: " . $e->getMessage());
                }
            }
            
            // Fallback to JSON file
            if (!$authenticated) {
                $resellersFile = __DIR__ . '/../data/resellers.json';
                if (file_exists($resellersFile)) {
                    $resellers = json_decode(file_get_contents($resellersFile), true);
                    foreach ($resellers as $reseller) {
                        if (($reseller['username'] === $username || $reseller['email'] === $username) 
                            && password_verify($password, $reseller['password'])) {
                            $_SESSION['reseller_logged_in'] = true;
                            $_SESSION['reseller_id'] = $reseller['id'];
                            $_SESSION['reseller_name'] = $reseller['name'];
                            $_SESSION['reseller_company'] = $reseller['company'];
                            $_SESSION['reseller_discount'] = $reseller['discount_percentage'] ?? 15;
                            $authenticated = true;
                            
                            header('Location: ' . $redirect);
                            exit;
                        }
                    }
                }
            }
            
            if (!$authenticated) {
                logSecurityEvent('login_failed', 'Invalid login attempt', ['site' => SITE_KEY, 'username' => $username]);
                $error = 'Invalid username or password.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reseller Login - <?php echo SITE_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: <?php echo SITE_COLOR; ?>;
            --white: #fff;
            --gray-200: #e2e8f0;
            --gray-600: #475569;
            --gray-800: #1e293b;
            --dark: #0f172a;
            --danger: #dc2626;
            --radius: 12px;
            --radius-lg: 16px;
            --shadow-xl: 0 20px 40px rgba(0,0,0,0.15);
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; }
        .login-page {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, var(--primary) 0%, color-mix(in srgb, var(--primary) 80%, black) 100%);
            padding: 24px;
        }
        .login-card {
            background: var(--white);
            border-radius: var(--radius-lg);
            padding: 48px;
            width: 100%;
            max-width: 420px;
            box-shadow: var(--shadow-xl);
            position: relative;
        }
        .login-header { text-align: center; margin-bottom: 32px; }
        .login-header .site-name {
            font-size: 28px;
            font-weight: 800;
            color: var(--primary);
            margin-bottom: 8px;
        }
        .login-header h1 { font-size: 20px; color: var(--dark); margin-bottom: 8px; }
        .login-header p { color: var(--gray-600); font-size: 14px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; font-weight: 500; margin-bottom: 8px; color: var(--gray-800); }
        .form-group input {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius);
            font-size: 16px;
            transition: border-color 0.2s ease;
        }
        .form-group input:focus { outline: none; border-color: var(--primary); }
        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: var(--danger);
            padding: 12px 16px;
            border-radius: var(--radius);
            margin-bottom: 20px;
            font-size: 14px;
        }
        .btn {
            display: inline-block;
            padding: 16px 24px;
            border-radius: var(--radius);
            font-weight: 600;
            text-decoration: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
        .btn-primary { background: var(--primary); color: white; width: 100%; }
        .btn-primary:hover { filter: brightness(0.9); }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 24px;
            color: var(--gray-600);
            text-decoration: none;
        }
        .back-link:hover { color: var(--primary); }
    </style>
</head>
<body>
    <div class="login-page">
        <div class="login-card">
            <div class="login-header">
                <div class="site-name"><?php echo SITE_NAME; ?></div>
                <h1>Reseller Login</h1>
                <p>Access your reseller portal</p>
            </div>
            
            <?php if ($error): ?>
                <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <?= outputHoneypot() ?>
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
                
                <div class="form-group">
                    <label for="username">Username or Email</label>
                    <input type="text" id="username" name="username" required 
                           value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"
                           autocomplete="username">
                </div>
                
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" required
                           autocomplete="current-password">
                </div>
                
                <button type="submit" class="btn btn-primary">Sign In</button>
            </form>
            
            <div style="text-align: center; margin-top: 24px; padding-top: 24px; border-top: 1px solid var(--gray-200);">
                <p style="color: var(--gray-600); font-size: 14px; margin-bottom: 8px;">Don't have an account?</p>
                <a href="register.php" style="color: var(--primary); font-weight: 600; text-decoration: none;">Apply to become a reseller &rarr;</a>
            </div>

            <a href="../" class="back-link">&larr; Back to <?php echo SITE_NAME; ?></a>
        </div>
    </div>
</body>
</html>
