<?php
// index.php — 로그인 (다크 테마 + 비디오 배경)
$_base = '/' . trim(str_replace(str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']??''), '', str_replace('\\','/',__DIR__)), '/') . '/';
if (!file_exists(__DIR__ . '/config/database.php')) { header('Location: '.$_base.'setup.php'); exit; }
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/auth.php';

if (isLoggedIn()) { header('Location: '.BASE_URL.'pages/home.php'); exit; }

// 시스템관리자의 테마에서 로그인 배경 비디오 가져오기
$loginVideoUrl = BASE_URL.'assets/bg-video.mp4';
$loginCardOpacity = 0.78;
$loginVideoDim = 0.65;
try {
    $dbLogin = (new Database())->getConnection();
    // 직접 업로드된 로그인 배경 파일 (최우선)
    $loginBgFiles = glob(__DIR__ . '/assets/login_bg.*');
    if ($loginBgFiles) {
        $loginVideoUrl = BASE_URL.'assets/' . basename($loginBgFiles[0]);
    }
    // 로그인 카드 투명도
    $opStmt = $dbLogin->query("SELECT rule_value FROM policy_rule WHERE rule_key='login_card_opacity'");
    if ($opStmt) { $opVal = $opStmt->fetchColumn(); if ($opVal !== false) $loginCardOpacity = floatval($opVal); }
    // 로그인 영상 밝기
    $dimStmt = $dbLogin->query("SELECT rule_value FROM policy_rule WHERE rule_key='login_video_dim'");
    if ($dimStmt) { $dimVal = $dimStmt->fetchColumn(); if ($dimVal !== false) $loginVideoDim = floatval($dimVal); }
} catch(Exception $e) {}

$error = '';
$info = $_GET['msg'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = (new Database())->getConnection();
    $result = login($db, trim($_POST['login_id'] ?? ''), $_POST['password'] ?? '');
    if (isset($result['success'])) {
        $_SESSION['show_login_popup'] = true;
        header('Location: '.BASE_URL.'pages/home.php');
        exit;
    } else {
        $error = $result['error'];
    }
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인 — AP MEDIA ONE</title>
    <?php
    $faviconFiles = glob(__DIR__ . '/assets/favicon.*');
    foreach ($faviconFiles as $ff) {
        $fext = strtolower(pathinfo($ff, PATHINFO_EXTENSION));
        if (in_array($fext, ['png','ico'])) {
            $ftype = $fext === 'ico' ? 'image/x-icon' : 'image/png';
            echo '<link rel="icon" type="'.$ftype.'" href="'.BASE_URL.'assets/'.basename($ff).'?v='.filemtime($ff).'">';
            echo '<link rel="shortcut icon" href="'.BASE_URL.'assets/'.basename($ff).'?v='.filemtime($ff).'">';
            break;
        }
    }
    ?>
    <link rel="stylesheet" href="<?=BASE_URL?>assets/css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;600;700;800&display=swap" rel="stylesheet">
</head>
<body>
<div class="login-page" style="--video-dim:<?= $loginVideoDim ?>;">
    <!-- 비디오 배경 -->
    <div class="video-bg">
        <video autoplay muted loop playsinline>
            <source src="<?= htmlspecialchars($loginVideoUrl) ?>" type="<?= str_ends_with($loginVideoUrl,'.webm')?'video/webm':'video/mp4' ?>">
        </video>
    </div>

    <div class="login-card" style="--login-card-opacity:<?= $loginCardOpacity ?>;background:rgba(14,14,18,<?= $loginCardOpacity ?>);">
        <?php $logoLoginFiles = glob(__DIR__ . '/assets/logo_login.*');
        $logoFiles = glob(__DIR__ . '/assets/logo.*');
        if ($logoLoginFiles): ?>
        <img src="<?=BASE_URL?>assets/<?= basename($logoLoginFiles[0]) ?>" style="max-height:6.5rem;max-width:18rem;object-fit:contain;margin-bottom:1.25rem;display:block;margin-left:auto;margin-right:auto;" alt="Logo">
        <?php elseif ($logoFiles): ?>
        <img src="<?=BASE_URL?>assets/<?= basename($logoFiles[0]) ?>" style="max-height:6.5rem;max-width:18rem;object-fit:contain;margin-bottom:1.25rem;display:block;margin-left:auto;margin-right:auto;" alt="Logo">
        <?php else: ?>
        <h1 style="font-size:1.5rem;margin-bottom:0.5rem;text-align:center;">◆ AP Media</h1>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <?php if ($info === 'registered'): ?>
            <div class="alert alert-success">✅ 회원가입이 완료되었습니다. 관리자 승인 후 로그인할 수 있습니다.</div>
        <?php elseif ($info === 'pw_changed'): ?>
            <div class="alert alert-success">✅ 비밀번호가 변경되었습니다.</div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <input type="text" id="login_id" name="login_id" required placeholder="아이디" autofocus>
            </div>
            <div class="form-group">
                <input type="password" id="password" name="password" required placeholder="비밀번호">
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;">로그인</button>
        </form>

        <div style="text-align:center;margin-top:1.25rem;padding-top:1rem;border-top:1px solid rgba(255,255,255,0.06);">
            <span style="font-size:var(--fs-sm);color:var(--text-tertiary);">계정이 없으신가요?</span>
            <a href="<?=BASE_URL?>register.php" style="font-size:var(--fs-sm);font-weight:600;margin-left:0.375rem;">회원가입</a>
        </div>
    </div>
</div>
<?php if (isset($_GET['logout'])): ?>
<div id="logoutPopup" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);z-index:9999;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);" onclick="this.style.display='none'">
    <div style="text-align:center;padding:2.5rem 3rem;background:rgba(12,12,16,0.85);border-radius:12px;backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,0.1);">
        <div style="font-size:1.5rem;font-weight:700;color:#eaeaea;margin-bottom:0.5rem;">AP Media의 하루가 저물었습니다..</div>
        <div style="font-size:0.9rem;color:rgba(255,255,255,0.6);">오늘도 수고한 당신을 응원합니다!</div>
        <div style="margin-top:1.25rem;font-size:0.75rem;color:rgba(255,255,255,0.3);">클릭하여 닫기</div>
    </div>
</div>
<script>setTimeout(()=>{const p=document.getElementById('logoutPopup');if(p)p.style.display='none';},5000);</script>
<?php endif; ?>
</body>
</html>
