<?php
/**
 * Modern Login Page
 */
ini_set('session.cookie_lifetime', 31536000);
ini_set('session.gc_maxlifetime', 31536000);
if (session_status() == PHP_SESSION_NONE) {
    session_set_cookie_params(31536000);
    session_start();
}

require_once 'includes/db.php';
require_once 'includes/config.php';

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: index");
    exit;
}

$error = '';

// Handle Google Login Callback
if (isset($_GET['code'])) {
    $token_url = 'https://oauth2.googleapis.com/token';
    $post_data = [
        'code' => $_GET['code'],
        'client_id' => GOOGLE_CLIENT_ID,
        'client_secret' => GOOGLE_CLIENT_SECRET,
        'redirect_uri' => GOOGLE_REDIRECT_URL,
        'grant_type' => 'authorization_code'
    ];

    $ch = curl_init($token_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    $response = curl_exec($ch);
    curl_close($ch);

    $token_data = json_decode($response, true);

    if (isset($token_data['access_token'])) {
        $userinfo_url = 'https://www.googleapis.com/oauth2/v2/userinfo?access_token=' . $token_data['access_token'];
        $ch = curl_init($userinfo_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $userinfo_response = curl_exec($ch);
        curl_close($ch);

        $google_user = json_decode($userinfo_response, true);

        if (isset($google_user['email'])) {
            $email = $google_user['email'];
            $name = $google_user['name'] ?? 'Google User';

            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if (!$user) {
                // Register new user
                $random_password = password_hash(bin2hex(random_bytes(8)), PASSWORD_DEFAULT);
                try {
                    $stmt_insert = $pdo->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
                    $stmt_insert->execute([$name, $email, $random_password]);
                    $user_id = $pdo->lastInsertId();
                    
                    $_SESSION['user_id'] = $user_id;
                    $_SESSION['user_name'] = $name;
                    $_SESSION['user_role'] = 'user'; 
                } catch (Exception $e) {
                    $error = "Registration failed: " . $e->getMessage();
                }
            } else {
                // Login existing user
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_role'] = $user['role'] ?? 'user';
            }

            if (empty($error)) {
                if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
                    header("Location: admin/dashboard");
                } else {
                    header("Location: index");
                }
                exit;
            }
        } else {
            $error = "Failed to fetch user information from Google.";
        }
    } else {
        $error = "Google login failed. Please try again.";
    }
}

// Normal Login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if (empty($email) || empty($password)) {
        $error = "Please enter both email and password.";
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            // Set Session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_role'] = $user['role'] ?? 'user';

            // Redirect based on role
            if (isset($user['role']) && $user['role'] === 'admin') {
                header("Location: admin/dashboard");
            } else {
                header("Location: index");
            }
            exit;
        } else {
            $error = "Invalid email or password.";
        }
    }
}

// Generate Google Login URL
$google_login_url = '';
if (defined('GOOGLE_CLIENT_ID') && !empty(GOOGLE_CLIENT_ID)) {
    $google_login_url = 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=' . GOOGLE_CLIENT_ID . '&redirect_uri=' . urlencode(GOOGLE_REDIRECT_URL) . '&scope=email%20profile';
}

$page_title = 'Login';
require_once 'includes/header.php';
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    .auth-container { 
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
        max-width: 450px; 
        margin: 80px auto; 
        background: #ffffff; 
        padding: 40px; 
        border-radius: 8px; 
        box-shadow: none; 
        border: 1px solid #e2e8f0; 
    }
    .auth-title { font-size: 1.8rem; font-weight: 700; color: #00059E; margin-bottom: 10px; text-align: center; }
    .auth-subtitle { color: #64748b; text-align: center; margin-bottom: 30px; font-size: 0.95rem; }
    .form-group { margin-bottom: 20px; }
    .form-group label { display: block; margin-bottom: 8px; font-weight: 500; color: #0f172a; }
    .form-control { width: 100%; padding: 12px 15px; border: 1px solid #e2e8f0; border-radius: 4px; outline: none; transition: all 0.3s ease; font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important; box-sizing: border-box; }
    .form-control:focus { border-color: #00059E; box-shadow: 0 0 0 3px rgba(0, 5, 158, 0.1); }
    .auth-btn { width: 100%; padding: 14px; font-size: 1.1rem; margin-top: 10px; background-color: #00059E !important; color: #ffffff !important; border: none; border-radius: 4px; cursor: pointer; transition: background 0.3s ease; font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
    .auth-btn:hover { background-color: #00037a !important; }
    
    .google-btn { 
        width: 100%; 
        padding: 12px 14px; 
        font-size: 1.05rem; 
        margin-top: 15px; 
        background-color: #ffffff !important; 
        color: #334155 !important; 
        border: 1px solid #cbd5e1; 
        border-radius: 4px; 
        cursor: pointer; 
        transition: all 0.3s ease; 
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important; 
        font-weight: 600; 
        display: flex; 
        align-items: center; 
        justify-content: center; 
        gap: 10px; 
        text-decoration: none; 
        box-sizing: border-box;
    }
    .google-btn:hover { 
        background-color: #f8fafc !important; 
        border-color: #94a3b8; 
    }

    .auth-footer { text-align: center; margin-top: 25px; color: #64748b; font-size: 0.95rem; }
    .auth-footer a { color: #00059E; font-weight: 600; text-decoration: none; }
    .auth-footer a:hover { text-decoration: underline; color: #00037a; }
    .alert-danger { background: #fee2e2; color: #ef4444; padding: 12px 15px; border-radius: 4px; margin-bottom: 20px; font-weight: 500; font-size: 0.9rem; border: 1px solid #f87171; }
</style>

<div class="container">
    <div class="auth-container">
        <h1 class="auth-title">Welcome Back</h1>
        <p class="auth-subtitle">Login to access your purchased products.</p>

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

        <form action="" method="POST">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" placeholder="email@example.com" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" placeholder="Enter your password" required>
            </div>
            <button type="submit" class="btn btn-primary auth-btn">Login Now</button>
        </form>

        <?php if(!empty($google_login_url)): ?>
        <div style="text-align: center; margin: 25px 0 10px 0; color: #94a3b8; font-weight: 600; position: relative; font-size: 0.85rem;">
            <hr style="border: none; border-top: 1px solid #e2e8f0; position: absolute; width: 100%; top: 50%; z-index: 1; margin: 0;">
            <span style="background: #ffffff; padding: 0 15px; position: relative; z-index: 2;">OR</span>
        </div>
        
        <a href="<?php echo htmlspecialchars($google_login_url); ?>" class="google-btn">
            <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd" clip-rule="evenodd" d="M24 9.5C27.54 9.5 30.71 10.74 33.22 12.87L40.23 5.86C35.91 1.95 30.34 0 24 0C14.54 0 6.36 5.48 2.37 13.51L10.57 19.87C12.56 13.79 17.81 9.5 24 9.5Z" fill="#EA4335"/>
                <path fill-rule="evenodd" clip-rule="evenodd" d="M47.53 24.5C47.53 22.8 47.23 21.17 46.68 19.64H24V28.91H37.19C36.63 31.86 34.92 34.42 32.44 36.08L40.45 42.29C45.13 37.97 47.53 31.82 47.53 24.5Z" fill="#4285F4"/>
                <path fill-rule="evenodd" clip-rule="evenodd" d="M10.57 28.13C10.05 26.54 9.75 24.81 9.75 24C9.75 23.19 10.05 21.46 10.57 19.87L2.37 13.51C0.87 16.5 0 19.98 0 24C0 28.02 0.87 31.5 2.37 34.49L10.57 28.13Z" fill="#FBBC05"/>
                <path fill-rule="evenodd" clip-rule="evenodd" d="M24 48C30.6 48 36.14 45.81 40.45 42.29L32.44 36.08C30.13 37.63 27.28 38.5 24 38.5C17.81 38.5 12.56 34.21 10.57 28.13L2.37 34.49C6.36 42.52 14.54 48 24 48Z" fill="#34A853"/>
            </svg>
            Continue with Google
        </a>
        <?php endif; ?>

        <div class="auth-footer">
            Don't have an account? <a href="register">Create Account</a>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
<?php require_once 'includes/mobile-nav.php'; ?>
