<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Profesyonel Radyo Hosting ve Web Tasarım Hizmetleri
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| ADMİN GİRİŞ EKRANI
|--------------------------------------------------------------------------
| login.php
| Okey Platformu Premium Yönetici Giriş Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

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

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

if (!isset($pdo) && isset($db) && $db instanceof PDO) {
    $pdo = $db;
}

function login_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function login_admin_image(?string $image): string
{
    $image = trim((string)$image);

    if ($image === '') {
        return '../assets/images/admin-default.png';
    }

    $image = trim(str_replace('\\', '/', $image));

    if (str_starts_with($image, 'http://') || str_starts_with($image, 'https://')) {
        return $image;
    }

    $imageName = basename($image);

    $paths = [
        [
            'disk' => __DIR__ . '/../uploads/users/' . $imageName,
            'url'  => '../uploads/users/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/user/' . $imageName,
            'url'  => '../uploads/user/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/' . $imageName,
            'url'  => '../uploads/' . $imageName,
        ],
    ];

    foreach ($paths as $path) {
        if (is_file($path['disk'])) {
            return $path['url'];
        }
    }

    return '../assets/images/admin-default.png';
}

if (!empty($_SESSION['admin_logged_in']) && !empty($_SESSION['admin_id'])) {
    header('Location: index.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = trim((string)($_POST['password'] ?? ''));

    if ($username === '' || $password === '') {
        $error = 'Kullanıcı adı ve şifre boş olamaz.';
    } else {
        try {
            if (!isset($pdo) || !($pdo instanceof PDO)) {
                throw new RuntimeException('Veritabanı bağlantısı bulunamadı.');
            }

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

            if (!$user) {
                throw new RuntimeException('Kullanıcı bulunamadı.');
            }

            $storedPassword = (string)($user['password'] ?? '');
            $passwordOk = false;

            if (password_verify($password, $storedPassword)) {
                $passwordOk = true;
            }

            if (!$passwordOk && $password === $storedPassword) {
                $passwordOk = true;
            }

            if (!$passwordOk && md5($password) === $storedPassword) {
                $passwordOk = true;
            }

            if (!$passwordOk) {
                throw new RuntimeException('Şifre hatalı.');
            }

            $role = strtolower((string)($user['role'] ?? ''));
            $status = strtolower((string)($user['status'] ?? 'active'));

            if (!in_array($role, ['admin', 'superadmin', 'super_admin', 'owner'], true)) {
                throw new RuntimeException('Yönetim paneline giriş yetkiniz yok.');
            }

            if (!in_array($status, ['active', 'aktif', '1'], true)) {
                throw new RuntimeException('Bu yönetici hesabı pasif durumdadır.');
            }

            session_regenerate_id(true);

            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_id'] = (int)($user['id'] ?? 0);
            $_SESSION['user_id'] = (int)($user['id'] ?? 0);
            $_SESSION['admin_name'] = trim((string)($user['name'] ?? '')) !== ''
                ? (string)$user['name']
                : (string)($user['username'] ?? 'Yönetici');
            $_SESSION['admin_username'] = (string)($user['username'] ?? '');
            $_SESSION['admin_email'] = (string)($user['email'] ?? '');
            $_SESSION['admin_role'] = $role;
            $_SESSION['admin_image'] = login_admin_image($user['image'] ?? '');

            header('Location: index.php');
            exit;

        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

$siteName = defined('SITE_NAME') ? SITE_NAME : 'Okey Platformu';
?>
<!doctype html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>Admin Giriş | <?= login_e($siteName) ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}

body{
    margin:0;
    min-height:100vh;
    font-family:Arial,Helvetica,sans-serif;
    color:#fff;
    background:
        radial-gradient(circle at 15% 15%,rgba(245,182,66,.25),transparent 32%),
        radial-gradient(circle at 85% 85%,rgba(185,0,0,.35),transparent 35%),
        linear-gradient(135deg,#050505,#111827 50%,#050505);
    display:flex;
    align-items:center;
    justify-content:center;
    padding:24px;
}

.login-wrapper{
    width:min(1150px,100%);
    min-height:660px;
    display:grid;
    grid-template-columns:1.15fr .85fr;
    overflow:hidden;
    border-radius:36px;
    background:rgba(8,8,12,.90);
    border:1px solid rgba(255,255,255,.10);
    box-shadow:0 45px 140px rgba(0,0,0,.75);
}

.login-showcase{
    position:relative;
    padding:58px;
    overflow:hidden;
    background:
        linear-gradient(135deg,rgba(245,182,66,.18),rgba(185,0,0,.14)),
        radial-gradient(circle at top right,rgba(255,255,255,.12),transparent 35%);
}

.login-showcase:after{
    content:"♠";
    position:absolute;
    right:35px;
    bottom:-45px;
    font-size:220px;
    color:rgba(245,182,66,.08);
    font-weight:900;
}

.system-badge{
    display:inline-flex;
    padding:10px 16px;
    border-radius:999px;
    background:rgba(245,182,66,.13);
    border:1px solid rgba(245,182,66,.34);
    color:#ffd47d;
    font-size:13px;
    font-weight:900;
}

.login-showcase h1{
    position:relative;
    z-index:2;
    margin:42px 0 18px;
    max-width:640px;
    font-size:58px;
    line-height:1.04;
    letter-spacing:-1.5px;
}

.login-showcase h1 span{
    color:#f5b642;
}

.login-showcase p{
    position:relative;
    z-index:2;
    max-width:560px;
    margin:0;
    color:#d8d8d8;
    font-size:17px;
    line-height:1.75;
}

.feature-grid{
    position:relative;
    z-index:2;
    margin-top:45px;
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:16px;
}

.feature-card{
    padding:20px;
    border-radius:24px;
    background:rgba(0,0,0,.32);
    border:1px solid rgba(255,255,255,.09);
}

.feature-card strong{
    display:block;
    color:#f5b642;
    font-size:24px;
    margin-bottom:7px;
}

.feature-card span{
    color:#b9b9b9;
    font-size:13px;
    line-height:1.5;
    font-weight:700;
}

.login-panel{
    display:flex;
    align-items:center;
    padding:50px;
    background:linear-gradient(180deg,rgba(15,15,18,.98),rgba(5,5,6,.98));
}

.login-box{
    width:100%;
}

.login-logo{
    text-align:center;
    margin-bottom:28px;
}

.logo-circle{
    width:88px;
    height:88px;
    margin:0 auto 16px;
    display:flex;
    align-items:center;
    justify-content:center;
    border-radius:28px;
    background:linear-gradient(135deg,#f5b642,#b90000);
    color:#111;
    font-size:42px;
    font-weight:900;
    box-shadow:0 18px 55px rgba(185,0,0,.32);
}

.login-logo h2{
    margin:0;
    color:#f5b642;
    font-size:36px;
    letter-spacing:1px;
}

.login-logo p{
    margin:9px 0 0;
    color:#bdbdbd;
    font-size:14px;
    font-weight:800;
}

.error{
    padding:15px 16px;
    margin-bottom:18px;
    border-radius:17px;
    background:rgba(185,0,0,.28);
    border:1px solid rgba(255,90,90,.48);
    color:#ffe0e0;
    font-size:14px;
    font-weight:800;
}

label{
    display:block;
    margin:16px 0 8px;
    color:#f1f1f1;
    font-size:14px;
    font-weight:900;
}

.input-wrap{
    position:relative;
}

.input{
    width:100%;
    height:60px;
    padding:0 54px 0 17px;
    border-radius:18px;
    border:1px solid rgba(255,255,255,.15);
    background:rgba(255,255,255,.065);
    color:#fff;
    outline:none;
    font-size:15px;
    transition:.2s ease;
}

.input:focus{
    border-color:#f5b642;
    background:rgba(255,255,255,.085);
    box-shadow:0 0 0 4px rgba(245,182,66,.12);
}

.toggle-pass{
    position:absolute;
    right:15px;
    top:50%;
    transform:translateY(-50%);
    border:0;
    background:transparent;
    color:#ffd47d;
    font-weight:900;
    cursor:pointer;
}

.login-button{
    width:100%;
    height:62px;
    margin-top:25px;
    border:0;
    border-radius:19px;
    background:linear-gradient(135deg,#ffd15c,#ff6b6b);
    color:#431313;
    font-size:16px;
    font-weight:900;
    cursor:pointer;
    box-shadow:0 18px 45px rgba(255,105,105,.23);
    transition:.2s ease;
}

.login-button:hover{
    transform:translateY(-2px);
    filter:brightness(1.06);
}

.login-footer{
    margin-top:24px;
    text-align:center;
    color:#8f98a8;
    font-size:12px;
    font-weight:800;
    line-height:1.8;
}

.login-footer a{
    color:#f5b642;
    text-decoration:none;
    font-weight:900;
}

.dev-line{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:3px;
    margin-top:2px;
}

.dev-name{
    color:#ff5db1;
    font-weight:900;
    font-size:14px;
}

.whatsapp-link{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    width:24px;
    height:24px;
    margin-left:2px;
    vertical-align:middle;
    line-height:1;
}

.whatsapp-link img{
    width:24px;
    height:24px;
    display:block;
    object-fit:contain;
    filter:drop-shadow(0 0 7px rgba(37,211,102,.85));
    transition:.25s;
}

.whatsapp-link:hover img{
    transform:scale(1.15);
}

@media(max-width:900px){
    .login-wrapper{
        grid-template-columns:1fr;
        min-height:auto;
    }

    .login-showcase{
        display:none;
    }

    .login-panel{
        padding:34px 24px;
    }
}
</style>
</head>

<body>

<div class="login-wrapper">

    <section class="login-showcase">
        <div class="system-badge">Premium Okey Yönetim Sistemi</div>

        <h1>
            <?= login_e($siteName) ?>
            <span>Admin Merkezi</span>
        </h1>

        <p>
            Oyuncu yönetimi, duyurular, indirme dosyaları, Gold paketleri,
            üyelik sistemi ve yönetici kontrolü için hazırlanmış premium panel.
        </p>

        <div class="feature-grid">
            <div class="feature-card">
                <strong>EXE</strong>
                <span>İndirmeli oyun sistemi</span>
            </div>

            <div class="feature-card">
                <strong>Gold</strong>
                <span>Paket ve üyelik yönetimi</span>
            </div>

            <div class="feature-card">
                <strong>Panel</strong>
                <span>Profesyonel yönetim merkezi</span>
            </div>
        </div>
    </section>

    <section class="login-panel">
        <form class="login-box" method="post" autocomplete="off">

            <div class="login-logo">
                <div class="logo-circle">♠</div>
                <h2>OKEY ADMIN</h2>
                <p>Güvenli Yönetim Paneli Girişi</p>
            </div>

            <?php if ($error !== ''): ?>
                <div class="error"><?= login_e($error) ?></div>
            <?php endif; ?>

            <label for="username">Kullanıcı Adı veya E-Posta</label>
            <div class="input-wrap">
                <input
                    class="input"
                    type="text"
                    id="username"
                    name="username"
                    value="<?= login_e($_POST['username'] ?? '') ?>"
                    required
                    autofocus
                >
            </div>

            <label for="password">Şifre</label>
            <div class="input-wrap">
                <input
                    class="input"
                    type="password"
                    id="password"
                    name="password"
                    required
                >
                <button type="button" class="toggle-pass" onclick="togglePassword()">Göster</button>
            </div>

            <button class="login-button" type="submit">
                Yönetim Paneline Giriş Yap
            </button>

            <div class="login-footer">
                Powered By <?= date('Y') ?>
                <a href="https://www.radyohost.biz" target="_blank" rel="noopener">
                    RadyoHost.BiZ
                </a>
                Web Teknolojileri

                <br>

                <span class="dev-line">
                    Developed By
                    <span class="dev-name">VoLKaN75</span>
                    <a href="https://wa.me/905415917536"
                       target="_blank"
                       rel="noopener"
                       class="whatsapp-link"
                       title="WhatsApp">
                        <img src="../uploads/footer/whatsapp.png" alt="WhatsApp">
                    </a>
                </span>
            </div>

        </form>
    </section>

</div>

<script>
function togglePassword(){
    const input = document.getElementById('password');
    const button = document.querySelector('.toggle-pass');

    if(input.type === 'password'){
        input.type = 'text';
        button.textContent = 'Gizle';
    }else{
        input.type = 'password';
        button.textContent = 'Göster';
    }
}
</script>

</body>
</html>