<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not admin - using functions from connection.php
if (!is_logged_in() || !is_user_type('admin')) {
    header("Location: ../login.php");
    exit();
}

// Get admin data
$admin_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM admin_users_surabaya WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$admin_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check if account is active, redirect to logout if not
if ($admin_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive admin attempted to access dashboard: " . $_SESSION['username']);
    
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login with message
    header("Location: ../login.php?error=inactive");
    exit();
}

// Set page title
$page_title = "Dashboard Admin";

// Log activity (if log_activity function still exists)
if (function_exists('log_activity')) {
    log_activity($conn, $admin_id, 'admin', 'Dashboard Access', 'Admin accessed dashboard');
}

// Get dashboard statistics
// 1. Total Color Code dan Stok
$total_color_code_query = "SELECT COUNT(*) as total_colors FROM master_color_panel_surabaya";
$total_stok_query = "SELECT COUNT(*) as total_stok FROM color_stock_items_surabaya";

$total_colors_result = $conn->query($total_color_code_query);
$total_stok_result = $conn->query($total_stok_query);

$total_colors = $total_colors_result->fetch_assoc()['total_colors'];
$total_stok = $total_stok_result->fetch_assoc()['total_stok'];

// 2. Total On Going (transaksi dengan status peminjaman "Dipinjam")
$ongoing_query = "SELECT COUNT(*) as total_ongoing FROM stock_transactions_surabaya WHERE status_peminjaman = 'Dipinjam'";
$ongoing_result = $conn->query($ongoing_query);
$total_ongoing = $ongoing_result->fetch_assoc()['total_ongoing'];

// 3. Total Dipinjam (jumlah code barang dengan status "Dipinjam")
$dipinjam_query = "SELECT COUNT(*) as total_dipinjam FROM color_stock_items_surabaya WHERE status = 'Dipinjam'";
$dipinjam_result = $conn->query($dipinjam_query);
$total_dipinjam = $dipinjam_result->fetch_assoc()['total_dipinjam'];

// 4. Total Overdue (transaksi peminjaman yang masih dipinjam dan overdue)
$overdue_query = "
    SELECT COUNT(DISTINCT st.id) as total_overdue 
    FROM stock_transactions_surabaya st 
    WHERE st.status_peminjaman = 'Dipinjam' 
    AND TIMESTAMPDIFF(MINUTE, st.tanggal_pengembalian, NOW()) > 15
";
$overdue_result = $conn->query($overdue_query);
$total_overdue = $overdue_result->fetch_assoc()['total_overdue'];

// 5. Total Renew (code barang dengan status "Renew")
$renew_query = "SELECT COUNT(*) as total_renew FROM color_stock_items_surabaya WHERE status = 'Renew'";
$renew_result = $conn->query($renew_query);
$total_renew = $renew_result->fetch_assoc()['total_renew'];

// 6. Total Tersedia (code barang dengan status "Tersedia")
$tersedia_query = "SELECT COUNT(*) as total_tersedia FROM color_stock_items_surabaya WHERE status = 'Tersedia'";
$tersedia_result = $conn->query($tersedia_query);
$total_tersedia = $tersedia_result->fetch_assoc()['total_tersedia'];

// Include header
include '../template_admin/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- CSS Styles -->
    <style>
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }
        
        .card-clickable {
            cursor: pointer;
        }
        
        .modal {
            display: none;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-overlay {
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
        }
        
        .modal-content {
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .reservation-link {
            color: #3b82f6;
            text-decoration: none;
            font-weight: 500;
        }
        
        .reservation-link:hover {
            color: #1d4ed8;
            text-decoration: underline;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-dipinjam {
            background-color: #dbeafe;
            color: #1e40af;
        }
        
        .status-overdue {
            background-color: #fee2e2;
            color: #dc2626;
        }
        
        .status-renew {
            background-color: #fef3c7;
            color: #d97706;
        }
    </style>

    <!-- Welcome Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Dashboard Admin</h1>
                <p class="text-gray-600 mt-2">Selamat datang, <?php echo htmlspecialchars($admin_data['username']); ?>!</p>
                <p class="text-sm text-gray-500">Master Color Panel System - <?php echo date('d M Y, H:i'); ?></p>
            </div>
            <div class="text-right">
                <div class="bg-blue-100 p-3 rounded-full">
                    <i class="fas fa-tachometer-alt text-3xl text-blue-500"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Dashboard Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
        <!-- Total Color Code dan Stok -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Color Code</h3>
                    <p class="text-3xl font-bold text-indigo-600 mt-2"><?php echo number_format($total_colors); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Total Stok: <?php echo number_format($total_stok); ?></p>
                </div>
                <div class="bg-indigo-100 p-3 rounded-full">
                    <i class="fas fa-palette text-2xl text-indigo-500"></i>
                </div>
            </div>
        </div>

        <!-- Total On Going -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover card-clickable" onclick="openModal('ongoingModal')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">On Going</h3>
                    <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo number_format($total_ongoing); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Transaksi Aktif</p>
                </div>
                <div class="bg-blue-100 p-3 rounded-full">
                    <i class="fas fa-clock text-2xl text-blue-500"></i>
                </div>
            </div>
        </div>

        <!-- Total Dipinjam -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover card-clickable" onclick="openModal('dipinjamModal')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Dipinjam</h3>
                    <p class="text-3xl font-bold text-green-600 mt-2"><?php echo number_format($total_dipinjam); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Code Barang</p>
                </div>
                <div class="bg-green-100 p-3 rounded-full">
                    <i class="fas fa-hand-holding text-2xl text-green-500"></i>
                </div>
            </div>
        </div>

        <!-- Total Overdue -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover card-clickable" onclick="openModal('overdueModal')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Overdue</h3>
                    <p class="text-3xl font-bold text-red-600 mt-2"><?php echo number_format($total_overdue); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Transaksi Terlambat</p>
                </div>
                <div class="bg-red-100 p-3 rounded-full">
                    <i class="fas fa-exclamation-triangle text-2xl text-red-500"></i>
                </div>
            </div>
        </div>

        <!-- Total Renew -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover card-clickable" onclick="openModal('renewModal')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Renew</h3>
                    <p class="text-3xl font-bold text-yellow-600 mt-2"><?php echo number_format($total_renew); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Code Barang</p>
                </div>
                <div class="bg-yellow-100 p-3 rounded-full">
                    <i class="fas fa-redo text-2xl text-yellow-500"></i>
                </div>
            </div>
        </div>

        <!-- Total Tersedia -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Tersedia</h3>
                    <p class="text-3xl font-bold text-purple-600 mt-2"><?php echo number_format($total_tersedia); ?></p>
                    <p class="text-sm text-gray-600 mt-1">Code Barang</p>
                </div>
                <div class="bg-purple-100 p-3 rounded-full">
                    <i class="fas fa-check-circle text-2xl text-purple-500"></i>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- Modals will be included here -->
<?php include 'dashboard_modals_admin.php'; ?>

<!-- JavaScript -->
<script>
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        // Load modal content via AJAX
        loadModalContent(modalId);
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
    }
}

function loadModalContent(modalId) {
    const modalBody = document.querySelector(`#${modalId} .modal-body`);
    if (modalBody) {
        modalBody.innerHTML = '<div class="text-center py-4"><i class="fas fa-spinner fa-spin text-2xl text-gray-400"></i><p class="text-gray-500 mt-2">Loading...</p></div>';
        
        // Determine which data to load based on modal
        let dataType = '';
        switch(modalId) {
            case 'ongoingModal':
                dataType = 'ongoing';
                break;
            case 'dipinjamModal':
                dataType = 'dipinjam';
                break;
            case 'overdueModal':
                dataType = 'overdue';
                break;
            case 'renewModal':
                dataType = 'renew';
                break;
        }
        
        if (dataType) {
            fetch('dashboard_data_admin.php?type=' + dataType)
                .then(response => response.text())
                .then(data => {
                    modalBody.innerHTML = data;
                })
                .catch(error => {
                    modalBody.innerHTML = '<div class="text-center py-4 text-red-500"><i class="fas fa-exclamation-triangle text-2xl"></i><p class="mt-2">Error loading data</p></div>';
                });
        }
    }
}

function redirectToReservation(reservationNumber) {
    window.location.href = 'persetujuan_formulir_admin.php?show_reservation=' + encodeURIComponent(reservationNumber);
}

// Close modal when clicking outside
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        const modal = e.target.closest('.modal');
        if (modal) {
            modal.classList.remove('active');
        }
    }
});

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const activeModal = document.querySelector('.modal.active');
        if (activeModal) {
            activeModal.classList.remove('active');
        }
    }
});
</script>

<?php include '../template_admin/footer.php'; ?>