<?php
session_start();

/**
 * Osama Electric - Ultimate Professional Login Portal
 * Modern Split-Screen UI with Mesh Gradients & Glassmorphism
 */

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

// Language Handling
if (isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'];
}
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// Translation strings
$texts = [
    'ar' => [
        'title' => 'بوابة الدخول | أسامة إلكتريك',
        'welcome' => 'تسجيل الدخول',
        'sub_welcome' => 'أدخل بياناتك للوصول إلى لوحة التحكم الموحدة',
        'username' => 'اسم المستخدم',
        'password' => 'كلمة المرور',
        'login_btn' => 'دخول النظام',
        'error_msg' => 'بيانات الدخول غير صحيحة، يرجى المحاولة مرة أخرى.',
        'copyright' => 'أسامة إلكتريك © 2025 - جميع الحقوق محفوظة',
        'lang_switch' => 'English',
        'hero_title' => 'مستقبل إدارة الطاقة بين يديك',
        'hero_desc' => 'نظام متطور يوفر لك الدقة الكاملة في إدارة المشتركين، الفوترة، والتحصيل المالي بأحدث التقنيات.'
    ],
    'en' => [
        'title' => 'Portal Login | Osama Electric',
        'welcome' => 'System Access',
        'sub_welcome' => 'Enter your credentials to access the unified dashboard',
        'username' => 'Username',
        'password' => 'Password',
        'login_btn' => 'Sign In Now',
        'error_msg' => 'Invalid credentials, please try again.',
        'copyright' => 'Osama Electric © 2025 - All Rights Reserved',
        'lang_switch' => 'العربية',
        'hero_title' => 'The Future of Energy Management',
        'hero_desc' => 'Advanced system providing full precision in customer management, billing, and financial collection.'
    ]
];

// Login Logic
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once 'db.php';
    $user_input = $_POST['username'] ?? '';
    $pass_input = $_POST['password'] ?? '';

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND status = 1 LIMIT 1");
        $stmt->execute([$user_input]);
        $user = $stmt->fetch();

        if ($user && password_verify($pass_input, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['permissions'] = json_decode($user['permissions'], true);

            $pdo->prepare("INSERT INTO audit_log (user_id, action) VALUES (?, ?)")
                ->execute([$user['id'], "Login: User authorized via professional portal"]);

            header("Location: dashboard.php");
            exit;
        } else {
            $error = $texts[$lang]['error_msg'];
        }
    } catch (PDOException $e) {
        $error = "System Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $texts[$lang]['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Cairo', sans-serif; background: #fff; overflow-x: hidden; }
        
        .mesh-bg {
            background-color: #0f172a;
            background-image: 
                radial-gradient(at 0% 0%, hsla(220,100%,15%,1) 0, transparent 50%), 
                radial-gradient(at 50% 0%, hsla(210,100%,10%,1) 0, transparent 50%), 
                radial-gradient(at 100% 0%, hsla(225,100%,20%,1) 0, transparent 50%);
        }

        .hero-animate {
            background: linear-gradient(-45deg, #1e3a8a, #1d4ed8, #2563eb, #3b82f6);
            background-size: 400% 400%;
            animation: gradient 15s ease infinite;
        }

        @keyframes gradient {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .glass-effect {
            background: rgba(255, 255, 255, 0.03);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .form-input {
            background: #f8fafc;
            border: 2px solid #f1f5f9;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            background: #fff;
            border-color: #3b82f6;
            box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.1);
        }
    </style>
</head>
<body class="min-h-screen">

    <div class="flex flex-col lg:flex-row min-h-screen">
        
        <!-- Left Section: Hero (Visual) -->
        <div class="lg:w-1/2 hero-animate hidden lg:flex flex-col justify-between p-16 text-white relative overflow-hidden">
            <!-- Decorative Elements -->
            <div class="absolute top-0 left-0 w-full h-full opacity-10">
                <div class="absolute top-10 left-10 w-64 h-64 bg-white rounded-full blur-3xl"></div>
                <div class="absolute bottom-10 right-10 w-96 h-96 bg-blue-400 rounded-full blur-3xl"></div>
            </div>

            <div class="relative z-10">
                <div class="flex items-center gap-4 mb-12">
                    <div class="w-12 h-12 bg-white/10 backdrop-blur-md rounded-2xl flex items-center justify-center text-2xl border border-white/20 shadow-xl">
                        <i class="fas fa-bolt text-blue-300"></i>
                    </div>
                    <span class="text-2xl font-black tracking-tighter uppercase">Osama Electric</span>
                </div>

                <div class="max-w-lg">
                    <h2 class="text-6xl font-black leading-tight mb-8">
                        <?= $texts[$lang]['hero_title'] ?>
                    </h2>
                    <p class="text-xl text-blue-100 font-semibold leading-relaxed opacity-80">
                        <?= $texts[$lang]['hero_desc'] ?>
                    </p>
                </div>
            </div>

            <div class="relative z-10">
                <div class="flex gap-8 items-center">
                    <div class="flex -space-x-4">
                        <div class="w-12 h-12 rounded-full border-4 border-blue-600 bg-slate-200 flex items-center justify-center text-slate-800 font-bold">A</div>
                        <div class="w-12 h-12 rounded-full border-4 border-blue-600 bg-slate-300 flex items-center justify-center text-slate-800 font-bold">B</div>
                        <div class="w-12 h-12 rounded-full border-4 border-blue-600 bg-slate-400 flex items-center justify-center text-slate-800 font-bold text-xs">+100</div>
                    </div>
                    <p class="text-sm font-bold text-blue-100 italic">Trusted by energy providers across the region.</p>
                </div>
            </div>
        </div>

        <!-- Right Section: Login Form -->
        <div class="lg:w-1/2 flex items-center justify-center p-8 bg-white relative">
            
            <!-- Language Switcher -->
            <div class="absolute top-10 <?= $is_ar ? 'left-10' : 'right-10' ?>">
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="bg-slate-50 hover:bg-slate-100 text-slate-600 px-6 py-2.5 rounded-full text-xs font-black transition-all border border-slate-100 flex items-center gap-2">
                    <i class="fas fa-globe text-blue-500"></i> <?= $texts[$lang]['lang_switch'] ?>
                </a>
            </div>

            <div class="w-full max-w-md">
                <div class="mb-12">
                    <div class="lg:hidden flex items-center gap-3 mb-8">
                        <div class="w-10 h-10 bg-blue-600 text-white rounded-xl flex items-center justify-center shadow-lg shadow-blue-200">
                            <i class="fas fa-bolt"></i>
                        </div>
                        <span class="text-xl font-black text-slate-800 uppercase tracking-tighter">Osama Electric</span>
                    </div>
                    <h3 class="text-4xl font-black text-slate-900 mb-4"><?= $texts[$lang]['welcome'] ?></h3>
                    <p class="text-slate-400 font-bold text-sm"><?= $texts[$lang]['sub_welcome'] ?></p>
                </div>

                <?php if($error): ?>
                    <div class="bg-rose-50 border border-rose-100 text-rose-600 p-4 rounded-2xl mb-8 font-bold flex items-center gap-3 text-sm animate-shake">
                        <i class="fas fa-exclamation-triangle"></i> <?= $error ?>
                    </div>
                <?php endif; ?>

                <form method="POST" class="space-y-8">
                    <div class="space-y-6">
                        <div class="relative">
                            <label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3 <?= $is_ar ? 'mr-2' : 'ml-2' ?>">
                                <?= $texts[$lang]['username'] ?>
                            </label>
                            <input type="text" name="username" required 
                                   class="form-input w-full p-5 rounded-3xl outline-none font-bold text-slate-700">
                            <i class="fas fa-user absolute <?= $is_ar ? 'left-6' : 'right-6' ?> bottom-6 text-slate-300"></i>
                        </div>

                        <div class="relative">
                            <label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3 <?= $is_ar ? 'mr-2' : 'ml-2' ?>">
                                <?= $texts[$lang]['password'] ?>
                            </label>
                            <input type="password" name="password" id="loginPassword" required 
                                   class="form-input w-full p-5 rounded-3xl outline-none font-bold text-slate-700">
                            <button type="button" onclick="togglePass()" class="absolute <?= $is_ar ? 'left-6' : 'right-6' ?> bottom-6 text-slate-300 hover:text-blue-500 transition">
                                <i id="eyeIcon" class="fas fa-eye-slash"></i>
                            </button>
                        </div>
                    </div>

                    <div class="pt-4">
                        <button type="submit" class="w-full p-6 bg-blue-600 hover:bg-slate-900 text-white rounded-[2.5rem] font-black text-lg shadow-2xl shadow-blue-200 transition-all duration-500 transform active:scale-95 flex items-center justify-center gap-4 group">
                            <span><?= $texts[$lang]['login_btn'] ?></span>
                            <i class="fas fa-arrow-<?= $is_ar ? 'left' : 'right' ?> opacity-50 group-hover:translate-x-<?= $is_ar ? '-3' : '3' ?> transition-transform"></i>
                        </button>
                    </div>
                </form>

                <div class="mt-16 text-center border-t border-slate-50 pt-8">
                    <p class="text-slate-400 text-[10px] font-black uppercase tracking-[0.2em] opacity-60">
                        <?= $texts[$lang]['copyright'] ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        function togglePass() {
            const pwd = document.getElementById('loginPassword');
            const icon = document.getElementById('eyeIcon');
            if (pwd.type === 'password') {
                pwd.type = 'text';
                icon.classList.replace('fa-eye-slash', 'fa-eye');
            } else {
                pwd.type = 'password';
                icon.classList.replace('fa-eye', 'fa-eye-slash');
            }
        }
    </script>
</body>
</html>