<?php
// login.php
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
session_start();

require_once 'db.php';

$error = "";

// Xử lý khi người dùng ấn nút Đăng nhập
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['btn_login'])) {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';

    if (!empty($username) && !empty($password)) {
        try {
            if (defined('PDO::SQLSRV_ATTR_ENCODING')) {
                $conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_UTF8);
            }

            $sql = "SELECT tk.id, tk.ten_dang_nhap, tk.mat_khau, tk.quyen, tk.trang_thai, 
                           tk.id_giang_vien, gv.ten_gv, gv.bo_mon 
                    FROM tai_khoan tk 
                    LEFT JOIN giang_vien gv ON tk.id_giang_vien = gv.id 
                    WHERE LTRIM(RTRIM(tk.ten_dang_nhap)) = :user";
                    
            $stmt = $conn->prepare($sql);
            $stmt->execute(array(':user' => $username));
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                if (isset($user['trang_thai']) && (int)$user['trang_thai'] === 0) {
                    $error = "✗ Tài khoản này hiện đang bị khóa!";
                } elseif (trim($user['mat_khau']) === $password) {
                    $_SESSION['user_id']       = $user['id'];
                    $_SESSION['username']      = $user['ten_dang_nhap'];
                    $_SESSION['quyen']         = $user['quyen'];
                    $_SESSION['id_giang_vien'] = $user['id_giang_vien'];
                    $_SESSION['ten_gv']        = !empty($user['ten_gv']) ? $user['ten_gv'] : 'Ban Quản Trị';
                    $_SESSION['bo_mon']        = !empty($user['bo_mon']) ? $user['bo_mon'] : '';

                    header("Location: index.php");
                    exit();
                } else {
                    $error = "✗ Mật khẩu nhập vào không chính xác!";
                }
            } else {
                $error = "✗ Không tìm thấy tên đăng nhập!";
            }
        } catch (PDOException $e) {
            $error = "✗ Lỗi CSDL: " . $e->getMessage();
        }
    } else {
        $error = "✗ Vui lòng nhập đầy đủ Tên đăng nhập và Mật khẩu!";
    }
}

// 1. LẤY THỐNG KÊ QUÂN SỐ, TIẾN SĨ, THẠC SĨ
$tong_quan_so = 0;
$so_luong_ts  = 0;
$so_luong_ths = 0;

try {
    $stmt_qs = $conn->query("SELECT COUNT(*) as total FROM giang_vien");
    if ($row = $stmt_qs->fetch(PDO::FETCH_ASSOC)) {
        $tong_quan_so = $row['total'];
    }

    $sql_ts = "SELECT COUNT(*) as total FROM giang_vien 
               WHERE hoc_vi LIKE N'%Tiến sĩ%' 
                  OR hoc_vi LIKE N'%Tiến sỹ%' 
                  OR hoc_vi LIKE '%TS%' 
                  OR hoc_ham LIKE N'%Tiến sĩ%' 
                  OR hoc_ham LIKE N'%Tiến sỹ%' 
                  OR hoc_ham LIKE '%TS%'";
    $stmt_ts = $conn->query($sql_ts);
    if ($row = $stmt_ts->fetch(PDO::FETCH_ASSOC)) {
        $so_luong_ts = $row['total'];
    }

    $sql_ths = "SELECT COUNT(*) as total FROM giang_vien 
                WHERE hoc_vi LIKE N'%Thạc sĩ%' 
                   OR hoc_vi LIKE N'%Thạc sỹ%' 
                   OR hoc_vi LIKE '%ThS%'";
    $stmt_ths = $conn->query($sql_ths);
    if ($row = $stmt_ths->fetch(PDO::FETCH_ASSOC)) {
        $so_luong_ths = $row['total'];
    }
} catch (PDOException $e) {}

// 2. LƯỢT TRUY CẬP
$luot_truy_cap = 0;
try {
    if (!isset($_SESSION['visited_count'])) {
        $_SESSION['visited_count'] = true;
        $conn->exec("UPDATE luot_truy_cap SET so_luot = so_luot + 1 WHERE id = 1");
    }
    $stmt_ltc = $conn->query("SELECT so_luot FROM luot_truy_cap WHERE id = 1");
    if ($row = $stmt_ltc->fetch(PDO::FETCH_ASSOC)) {
        $luot_truy_cap = $row['so_luot'];
    }
} catch (PDOException $e) {
    $file_counter = 'counter.txt';
    if (!file_exists($file_counter)) {
        file_put_contents($file_counter, '1');
        $luot_truy_cap = 1;
    } else {
        $luot_truy_cap = (int)file_get_contents($file_counter);
        if (!isset($_SESSION['visited_count'])) {
            $_SESSION['visited_count'] = true;
            $luot_truy_cap++;
            file_put_contents($file_counter, (string)$luot_truy_cap);
        }
    }
}

// 3. LẤY DỮ LIỆU LỊCH CÔNG TÁC
$lich_theo_thu = array();
try {
    $stmt_lct = $conn->query("SELECT * FROM lich_cong_tac ORDER BY id ASC");
    $ds_lich_cong_tac = $stmt_lct->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($ds_lich_cong_tac as $lct) {
        $thu = $lct['thu'];
        if (!isset($lich_theo_thu[$thu])) {
            $lich_theo_thu[$thu] = array();
        }
        $lich_theo_thu[$thu][] = $lct;
    }
} catch (PDOException $e) {}

// 4. LẤY DỮ LIỆU SỰ KIỆN SẮP DIỄN RA
$ds_su_kien = array();
try {
    $stmt_sk = $conn->query("SELECT TOP 5 * FROM su_kien ORDER BY id DESC");
    if ($stmt_sk) {
        $ds_su_kien = $stmt_sk->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {}
?>

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lịch Công tác & Đăng nhập - Khoa TT-TCĐT</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Arial, sans-serif; }
        
        body { 
            background: #ffffff; 
            height: 100vh; 
            overflow: hidden; 
            display: flex; 
            flex-direction: column; 
        }
        
        .split-container { 
            display: flex; 
            width: 100%; 
            flex: 1; 
            flex-wrap: nowrap;
            max-width: 1400px;
            margin: 0 auto;
            padding: 15px 20px;
            gap: 20px;
            min-height: 0; 
            align-items: center; 
            justify-content: center;
        }
        
        /* CỘT TRÁI (LỊCH CÔNG TÁC & SỰ KIỆN) */
        .left-panel { 
            flex: 2.8; 
            background: #ffffff; 
            padding: 20px; 
            border-radius: 12px; 
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1); 
            overflow-y: auto; 
            display: block; /* Hiện mặc định trên PC */
        }
        .left-panel h2 { 
            color: #003366; font-size: 18px; text-transform: uppercase; 
            margin-bottom: 15px; border-bottom: 3px solid #003366; 
            padding-bottom: 8px; display: flex; justify-content: space-between; align-items: center; 
        }
        
        .table-lct { width: 100%; border-collapse: collapse; font-size: 13.5px; border-top: 1px solid #cbd5e1; }
        .table-lct th { background: #003366; color: white; text-align: center; font-weight: bold; padding: 8px; border: 1px solid #cbd5e1; }
        .table-lct td { padding: 8px; text-align: left; vertical-align: middle; border-left: 1px solid #cbd5e1; border-right: 1px solid #cbd5e1; }
        .row-solid td { border-bottom: 1px solid #94a3b8; }
        .row-dashed td { border-bottom: 1px dashed #cbd5e1; }
        .table-lct td.col-thu { font-weight: bold; color: #003366; text-align: center; background: #f1f5f9; width: 85px; border-bottom: 1px solid #94a3b8; }
        .table-lct td.col-gio { font-weight: 600; color: #d35400; text-align: center; width: 105px; }
        .table-lct tr:hover td:not(.col-thu) { background: #f8fafc; }
        
        .events-wrapper {
            margin-top: 15px;
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
            border-left: 4px solid #f59e0b;
            border-radius: 6px;
            padding: 10px 14px;
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.12);
        }
        .events-title {
            color: #b45309;
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }
        .bell-icon {
            display: inline-block;
            margin-right: 6px;
            font-size: 15px;
            animation: ringBell 2s infinite;
            transform-origin: top center;
        }
        @keyframes ringBell {
            0%, 100% { transform: rotate(0deg); }
            10% { transform: rotate(15deg); }
            20% { transform: rotate(-10deg); }
            30% { transform: rotate(15deg); }
            40% { transform: rotate(-10deg); }
            50% { transform: rotate(0deg); }
        }
        .event-list { display: flex; flex-direction: column; gap: 8px; }
        .event-item {
            background: #ffffff;
            border: 1px solid #fde68a;
            padding: 8px 10px;
            border-radius: 5px;
            transition: all 0.2s ease;
        }
        .event-item:hover { transform: translateX(4px); border-color: #f59e0b; }
        .event-time { font-size: 11px; color: #d97706; font-weight: 700; margin-bottom: 2px; }
        .event-name { font-size: 13.5px; color: #1e293b; font-weight: 600; line-height: 1.3; margin-bottom: 2px; }
        .event-location { font-size: 12px; color: #64748b; font-style: italic; }

        /* CỘT PHẢI (LOGIN FORM) */
        .right-panel { 
            flex: 1.2; 
            display: flex; 
            justify-content: center; 
            min-width: 320px; 
        }
        
        .login-card { 
            background: #4b5320; 
            padding: 25px 20px; 
            border-radius: 12px; 
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3), 0 0 15px rgba(75, 83, 32, 0.4); 
            width: 100%; 
            max-width: 380px; 
            color: #ffffff; 
        }

        .logo-container { text-align: center; margin-bottom: 15px; }
        .logo-container img { 
            width: 230px; height: 230px; object-fit: contain; border-radius: 50%; 
            border: 3px solid #eab308; box-shadow: 0 0 15px rgba(234, 179, 8, 0.6), 0 0 8px rgba(255, 255, 255, 0.4); 
            padding: 4px; background: rgba(255, 255, 255, 0.1); transition: all 0.3s ease;
        }
        .logo-container img:hover { transform: scale(1.05); }

        .login-card h3 { color: #ffffff; text-align: center; margin-bottom: 3px; font-size: 17px; text-transform: uppercase; font-weight: bold; letter-spacing: 0.5px; }
        .login-card p.sub { text-align: center; color: #d1d5db; font-size: 12.5px; margin-bottom: 15px; }
        
        .form-group { margin-bottom: 12px; }
        .form-group label { display: block; margin-bottom: 4px; font-weight: bold; color: #ffffff; font-size: 13px; }
        .form-group input { width: 100%; padding: 9px 12px; border: 1px solid #71717a; border-radius: 6px; font-size: 13.5px; outline: none; background: #ffffff; color: #1e293b; }
        .form-group input:focus { border-color: #eab308; box-shadow: 0 0 8px rgba(234, 179, 8, 0.6); }
        
        .btn-login { 
            background: #eab308; color: #1c1917; padding: 10px; border: none; width: 100%; 
            border-radius: 6px; font-size: 14.5px; font-weight: bold; cursor: pointer; transition: 0.2s; margin-top: 5px; 
            text-transform: uppercase;
        }
        .btn-login:hover { background: #ca8a04; color: #ffffff; }
        
        /* THỐNG KÊ CHI TIẾT */
        .thong-ke-container {
            margin-top: 15px; padding-top: 10px; border-top: 1px dashed rgba(255, 255, 255, 0.3);
            display: grid; grid-template-columns: 1fr 1fr; gap: 8px; text-align: center;
        }
        .thong-ke-item { background: rgba(255, 255, 255, 0.1); padding: 8px 4px; border-radius: 6px; border: 1px solid rgba(255, 255, 255, 0.15); }
        .thong-ke-item .label { font-size: 11.5px; color: #d1d5db; display: block; margin-bottom: 2px; }
        .thong-ke-item .val { font-size: 15px; font-weight: bold; color: #fef08a; }

        .error-msg { background: #f8d7da; color: #721c24; padding: 8px; border-radius: 4px; font-size: 12px; font-weight: bold; margin-bottom: 12px; text-align: center; border: 1px solid #f5c6cb; }

        .copyright-footer {
            width: 100%; background: #ffffff; color: #475569; text-align: center;
            padding: 10px 20px; font-size: 12px; font-weight: 500;
            border-top: 1px solid #e2e8f0; line-height: 1.4; flex-shrink: 0; 
        }

        /* ========================================================
           RESPONSIVE MOBILE VIEW (< 900px)
           ======================================================== */
        @media (max-width: 900px) {
            body { height: auto; overflow: auto; background-color: #f4f6f9; }
            .split-container { 
                flex-direction: column; 
                padding: 15px; 
                height: 100vh; /* Phủ kín màn hình trên điện thoại */
                align-items: center; 
                justify-content: center;
            }
            /* ẨN TOÀN BỘ CỘT TRÁI KHI MỞ BẰNG ĐIỆN THOẠI */
            .left-panel { display: none !important; }
            
            /* CHO CỘT PHẢI CĂN GIỮA MÀN HÌNH */
            .right-panel { flex: none; width: 100%; height: auto !important; display: flex; justify-content: center; align-items: center;}
        }
    </style>
</head>
<body>

<div class="split-container">
    <div class="left-panel">
        <h2>
            <span>📅 LỊCH CÔNG TÁC</span>
            <!--<a href="index.php" style="font-size: 12px; color: #003366; text-decoration: underline; font-weight: normal;">[Xem lịch tuần chính]</a> -->
        </h2>

        <table class="table-lct">
            <thead>
                <tr>
                    <th>Thứ</th>
                    <th>Khung giờ</th>
                    <th>Nội dung công việc</th>
                    <th>Phụ trách</th>
                    <th>TP Tham gia</th>
                    <th>Ghi chú</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($lich_theo_thu)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; color: #94a3b8; padding: 20px; border-bottom: 1px solid #cbd5e1;">Chưa có lịch công tác chung nào được cập nhật.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($lich_theo_thu as $thu => $cac_ca): ?>
                        <?php 
                        $so_ca = count($cac_ca);
                        foreach ($cac_ca as $index => $lct): 
                            $is_last = ($index === $so_ca - 1);
                            $row_class = $is_last ? "row-solid" : "row-dashed";
                        ?>
                            <tr class="<?php echo $row_class; ?>">
                                <?php if ($index === 0): ?>
                                    <td class="col-thu" rowspan="<?php echo $so_ca; ?>">
                                        <?php echo htmlspecialchars($thu); ?>
                                    </td>
                                <?php endif; ?>
                                
                                <td class="col-gio"><?php echo htmlspecialchars($lct['khung_gio']); ?></td>
                                <td><?php echo nl2br(htmlspecialchars($lct['noi_dung'] ?? '')); ?></td>
                                <td style="font-weight: 600; color: #1e293b;"><?php echo htmlspecialchars($lct['phu_trach'] ?? ''); ?></td>
                                <td><?php echo htmlspecialchars($lct['tp_tham_gia'] ?? ''); ?></td>
                                <td style="color: #64748b; font-style: italic;"><?php echo htmlspecialchars($lct['ghi_chu'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <div class="events-wrapper">
            <div class="events-title">
                <span class="bell-icon">🔔</span> Thông báo & Sự kiện sắp diễn ra
            </div>
            
            <div class="event-list">
                <?php if (empty($ds_su_kien)): ?>
                    <div class="event-item" style="text-align: center; color: #64748b; padding: 6px;">
                        Chưa có sự kiện nào sắp diễn ra.
                    </div>
                <?php else: ?>
                    <?php foreach ($ds_su_kien as $sk): ?>
                        <div class="event-item">
                            <div class="event-time">⏰ <?php echo htmlspecialchars($sk['thoi_gian'] ?? ''); ?></div>
                            <div class="event-name"><?php echo htmlspecialchars($sk['ten_su_kien'] ?? ''); ?></div>
                            <?php if (!empty($sk['dia_diem'])): ?>
                                <div class="event-location">📍 <?php echo htmlspecialchars($sk['dia_diem']); ?></div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="right-panel">
        <div class="login-card">
            <div class="logo-container">
                <img src="uploads/logo.png" alt="Logo Khoa">
            </div>
            
            <h3>ĐĂNG NHẬP HỆ THỐNG</h3>
            <p class="sub">Khoa Thông tin - Tác chiến điện tử</p>
            
            <?php if(!empty($error)): ?>
                <div class="error-msg"><?php echo $error; ?></div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label>Tên đăng nhập:</label>
                    <input type="text" name="username" placeholder="Nhập tài khoản..." required autocomplete="off" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                </div>
                <div class="form-group">
                    <label>Mật khẩu:</label>
                    <input type="password" name="password" placeholder="••••••••" required>
                </div>
                <button type="submit" name="btn_login" class="btn-login">🔑 ĐĂNG NHẬP</button>
                
                <div class="thong-ke-container">
                    <div class="thong-ke-item">
                        <span class="label">👥 Tổng quân số</span>
                        <span class="val"><?php echo $tong_quan_so; ?></span>
                    </div>
                    <div class="thong-ke-item">
                        <span class="label">🎓 Tiến sĩ</span>
                        <span class="val"><?php echo $so_luong_ts; ?></span>
                    </div>
                    <div class="thong-ke-item">
                        <span class="label">📚 Thạc sĩ</span>
                        <span class="val"><?php echo $so_luong_ths; ?></span>
                    </div>
                    <div class="thong-ke-item">
                        <span class="label">👁️ Lượt truy cập</span>
                        <span class="val"><?php echo number_format($luot_truy_cap); ?></span>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="copyright-footer">
    Thiết kế bởi Hoàng Quốc Huy, Học viện Lục Quân, Lâm Đồng, 2026<br>
    Phone: 0868520052 | Email: huy.hvktqs45@gmail.com
</div>

<script>
    function syncPanelHeight() {
        var loginCard = document.querySelector('.login-card');
        var leftPanel = document.querySelector('.left-panel');
        
        if (loginCard && leftPanel) {
            if (window.innerWidth > 900) {
                // PC: Khớp chiều cao cột trái bằng cột phải
                leftPanel.style.display = 'block';
                leftPanel.style.height = loginCard.offsetHeight + 'px';
            } else {
                // Điện thoại: Đã ẩn cột trái bằng CSS, nên reset lại JS cho an toàn
                leftPanel.style.display = 'none';
                leftPanel.style.height = 'auto';
            }
        }
    }
    window.addEventListener('load', syncPanelHeight);
    window.addEventListener('resize', syncPanelHeight);
</script>

</body>
</html>