<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Initialize DB safely
try {
    $db = db();
} catch (Exception $e) {
    die("Database Connection Error: " . $e->getMessage());
}

require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/helpers.php';

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

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (empty($email) || empty($password)) {
        $error = __('fill_all_fields');
    } else {
        $stmt = $db->prepare("SELECT id, name, password, role_id, active FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && $user['active']) {
            if (password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                
                $update = $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $update->execute([$user['id']]);
                
                header("Location: dashboard.php");
                exit;
            } else {
                $error = __('invalid_credentials');
            }
        } else {
            $error = __('invalid_credentials');
        }
    }
}

// Fetch site settings for branding
try {
    $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('company_name', 'company_logo')");
    $settings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    $settings = [];
}
$site_name = !empty($settings['company_name']) ? $settings['company_name'] : 'Hospital Management';
$site_logo = !empty($settings['company_logo']) ? $settings['company_logo'] : null;

?>
<!DOCTYPE html>
<html lang="<?php echo get_lang_code(); ?>" dir="<?php echo get_dir(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('login'); ?> - <?php echo htmlspecialchars($site_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <?php if (is_rtl()): ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <?php endif; ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f4f7f6;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            width: 100%;
            max-width: 400px;
            border: none;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
            border-radius: 10px;
            overflow: hidden;
        }
        .login-header {
            background-color: #002D62;
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .login-body {
            background-color: white;
            padding: 40px 30px;
        }
        .form-control:focus {
            box-shadow: none;
            border-color: #002D62;
        }
        .btn-primary {
            background-color: #002D62;
            border-color: #002D62;
            padding: 10px;
            font-weight: 500;
        }
        .btn-primary:hover {
            background-color: #001f44;
            border-color: #001f44;
        }
    </style>
</head>
<body>

<div class="login-card">
    <div class="login-header">
        <?php if ($site_logo): ?>
            <img src="<?php echo htmlspecialchars($site_logo); ?>" alt="Logo" class="img-fluid mb-3" style="max-height: 60px;">
        <?php else: ?>
            <div class="mb-3">
                <i class="bi bi-hospital display-4"></i>
            </div>
        <?php endif; ?>
        <h4 class="mb-0 fw-bold"><?php echo htmlspecialchars($site_name); ?></h4>
        <p class="mb-0 opacity-75 small mt-1"><?php echo __('login_to_continue'); ?></p>
    </div>
    <div class="login-body">
        <?php if ($error): ?>
            <div class="alert alert-danger text-center py-2 mb-4 small">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="mb-3">
                <label class="form-label text-secondary small fw-bold"><?php echo __('email'); ?></label>
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-envelope"></i></span>
                    <input type="email" name="email" class="form-control bg-light border-start-0" placeholder="name@example.com" required autofocus>
                </div>
            </div>
            <div class="mb-4">
                <label class="form-label text-secondary small fw-bold"><?php echo __('password'); ?></label>
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-lock"></i></span>
                    <input type="password" name="password" class="form-control bg-light border-start-0" placeholder="••••••••" required>
                </div>
            </div>
            <button type="submit" class="btn btn-primary w-100 mb-3 shadow-sm">
                <?php echo __('login'); ?> <i class="bi bi-arrow-right ms-1"></i>
            </button>
            
            <div class="text-center">
                <a href="#" class="text-decoration-none small text-muted"><?php echo __('forgot_password'); ?></a>
            </div>
        </form>
    </div>
    <div class="bg-light py-3 text-center border-top">
        <small class="text-muted">
             &copy; <?php echo date('Y'); ?> Flatlogic. All rights reserved.
        </small>
    </div>
</div>

</body>
</html>