<?php
ob_start();
session_start();
require_once 'config/database.php';
require_once 'includes/translation.php';

// Force logout if requested or if session is broken
if (isset($_GET['logout']) || isset($_GET['reset'])) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "admin_dashboard.php");
    exit();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    
    if (empty($username) || empty($password)) {
        $error = __('username_password_required');
    } else {
        try {
            $db = new Database();
            $conn = $db->getConnection();
            
            $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && $password === $user['password']) {
                if ($user['is_active']) {
                    // تحميل البيانات الأساسية
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['full_name'] = $user['full_name'];
                    $_SESSION['role'] = $user['role'];
                    $_SESSION['email'] = $user['email'];
                    
                    // Log login activity
                    $stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, ip_address, user_agent) VALUES (?, ?, ?, ?)");
                    $stmt->execute([
                        $user['id'],
                        __('login_activity'),
                        $_SERVER['REMOTE_ADDR'] ?? null,
                        $_SERVER['HTTP_USER_AGENT'] ?? null
                    ]);
                    
                    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "index.php");
                    exit();
                } else {
                    $error = __('account_inactive');
                }
            } else {
                $error = __('invalid_credentials');
            }
        } catch (Exception $e) {
            $error = __('database_error');
            error_log("Login error: " . $e->getMessage());
        }
    }
}
?>

<!DOCTYPE html>
<html lang="<?php echo Translation::getLanguage(); ?>" dir="<?php echo Translation::getDirection(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('login') . ' - ' . __('system_name'); ?></title>
    <link rel="icon" type="image/png" href="assets/images/1222f7f3-2c1c-4177-8f88-794699164d74.png">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/rtl-ltr.css" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #5e35b1 0%, #4c2c92 100%);
            --accent-color: #5e35b1;
        }

        * {
            box-sizing: border-box;
            font-family: 'Cairo', 'Tajawal', sans-serif;
        }
        
        body {
            background: #f1f5f9;
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 20px 20px;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
        }
        
        .login-container {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            overflow: hidden;
            max-width: 420px;
            width: 100%;
            border: 1px solid #e2e8f0;
        }
        
        .login-header {
            background: var(--primary-gradient);
            padding: 40px 20px;
            text-align: center;
            color: white;
        }

        .login-form {
            padding: 40px 32px;
        }
        
        .logo-circle {
            width: 64px;
            height: 64px;
            background: white;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }

        .logo-circle i {
            font-size: 32px;
            color: #5e35b1;
        }
        
        .hospital-title {
            font-size: 1.1rem;
            font-weight: 800;
            margin-bottom: 8px;
            letter-spacing: -0.025em;
        }
        
        .hospital-subtitle {
            font-size: 0.8rem;
            opacity: 0.8;
        }
        
        .form-label {
            font-weight: 600;
            color: #475569;
            margin-bottom: 8px;
            font-size: 0.8rem;
            display: block;
        }
        
        .form-control {
            border-radius: 12px;
            border: 1.5px solid #e2e8f0;
            padding: 10px 14px;
            font-size: 0.9rem;
            transition: all 0.2s;
            background: #f8fafc;
        }
        
        .form-control:focus {
            border-color: var(--accent-color);
            background: white;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .btn-login {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px;
            font-weight: 700;
            width: 100%;
            margin-top: 24px;
            transition: all 0.2s;
            cursor: pointer;
            font-size: 0.9rem;
        }
        
        .btn-login:hover {
            transform: translateY(-1px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            opacity: 0.9;
        }

        .error-message {
            background: #fef2f2;
            color: #dc2626;
            padding: 12px;
            border-radius: 12px;
            font-size: 0.8rem;
            margin-bottom: 20px;
            border: 1px solid #fee2e2;
            display: flex;
            align-items: center;
            gap: 8px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <div class="logo-circle">
                <i class="fas fa-hospital"></i>
            </div>
            <h1 class="hospital-title"><?php echo __('system_name'); ?></h1>
            <p class="hospital-subtitle"><?php echo __('hospital_name'); ?></p>
        </div>
        
        <div class="login-form">
            <?php if ($error): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="mb-4">
                    <label class="form-label"><?php echo __('username_or_email'); ?></label>
                    <input type="text" name="username" class="form-control" placeholder="<?php echo __('enter_username'); ?>" required autofocus>
                </div>
                
                <div class="mb-4">
                    <label class="form-label"><?php echo __('password'); ?></label>
                    <input type="password" name="password" class="form-control" placeholder="<?php echo __('enter_password'); ?>" required>
                </div>

                <button type="submit" class="btn-login">
                    <?php echo __('login'); ?>
                    <i class="fas fa-sign-in-alt ms-2"></i>
                </button>
            </form>
        </div>
    </div>
</body>
</html>
<?php ob_end_flush(); ?>
