<?php
// Start session
session_start();
// Include database connection
require_once "../config/connection.php";
// Redirect if not borrower user - using functions from connection.php
if (!is_logged_in() || !is_user_type('borrower')) {
    header("Location: ../login.php");
    exit();
}
// Get borrower data
$borrower_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM borrower_users WHERE id = ?");
$stmt->bind_param("i", $borrower_id);
$stmt->execute();
$borrower_data = $stmt->get_result()->fetch_assoc();
$stmt->close();
// Check if account is active, redirect to logout if not
if ($borrower_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive borrower 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";
// Log borrower access
log_activity($conn, $borrower_id, 'borrower', 'Dashboard Access', 'borrower user accessed dashboard');
// Include header
include '../template_peminjam/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-4 md:p-6 overflow-auto bg-gray-50">
    <!-- Welcome Section -->
    <div class="bg-white rounded-lg shadow-sm border p-6 mb-6">
        <div class="flex items-center mb-4">
            <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mr-4">
                <i class="fas fa-paint-brush text-green-600 text-xl"></i>
            </div>
            <div>
                <h2 class="text-xl font-semibold text-gray-800">Selamat Datang, <?php echo htmlspecialchars($borrower_data['nama_borrower']); ?></h2>
                <p class="text-gray-600 text-sm">Master Color Panel - Sistem Manajemen Peminjaman</p>
            </div>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                <i class="fas fa-id-card text-green-600 mr-3"></i>
                <div>
                    <p class="text-xs text-gray-500">NIK / ID</p>
                    <p class="font-medium text-gray-800"><?php echo htmlspecialchars($borrower_data['nik']); ?></p>
                </div>
            </div>
            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                <i class="fas fa-user text-green-600 mr-3"></i>
                <div>
                    <p class="text-xs text-gray-500">Nama Lengkap</p>
                    <p class="font-medium text-gray-800"><?php echo htmlspecialchars($borrower_data['nama_borrower']); ?></p>
                </div>
            </div>
            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                <i class="fas fa-map-marker-alt text-green-600 mr-3"></i>
                <div>
                    <p class="text-xs text-gray-500">Lokasi Kerja</p>
                    <p class="font-medium text-gray-800"><?php echo htmlspecialchars($borrower_data['lokasi_posisi']); ?></p>
                </div>
            </div>
        </div>
        
        <div class="mt-4 flex justify-end">
            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm <?php echo $borrower_data['status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                <i class="fas fa-<?php echo $borrower_data['status'] == 'active' ? 'check-circle' : 'times-circle'; ?> mr-1"></i>
                Status: <?php echo $borrower_data['status'] == 'active' ? 'Aktif' : 'Nonaktif'; ?>
            </span>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <?php
        // Get quick statistics
        $stats_stmt = $conn->prepare("
            SELECT 
                COUNT(*) as total_peminjaman,
                COUNT(CASE WHEN status_peminjaman = 'Dipinjam' THEN 1 END) as sedang_dipinjam,
                COUNT(CASE WHEN status_peminjaman = 'Dikembalikan' THEN 1 END) as selesai_dipinjam
            FROM stock_transactions 
            WHERE borrower_id = ?
        ");
        $stats_stmt->bind_param("i", $borrower_id);
        $stats_stmt->execute();
        $stats = $stats_stmt->get_result()->fetch_assoc();
        $stats_stmt->close();
        ?>
        
        <!-- Total Peminjaman -->
        <div class="bg-white rounded-lg shadow-sm border p-4 hover:shadow-md transition-shadow cursor-pointer" onclick="toggleTotalModal()">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600">Total Peminjaman</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $stats['total_peminjaman']; ?></p>
                </div>
                <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clipboard-list text-green-600"></i>
                </div>
            </div>
        </div>

        <!-- Sedang Dipinjam -->
        <div class="bg-white rounded-lg shadow-sm border p-4 hover:shadow-md transition-shadow cursor-pointer" onclick="toggleSedangModal()">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600">Sedang Dipinjam</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $stats['sedang_dipinjam']; ?></p>
                </div>
                <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clock text-yellow-600"></i>
                </div>
            </div>
        </div>

        <!-- Selesai Dipinjam -->
        <div class="bg-white rounded-lg shadow-sm border p-4 hover:shadow-md transition-shadow cursor-pointer" onclick="toggleSelesaiModal()">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600">Selesai Dipinjam</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $stats['selesai_dipinjam']; ?></p>
                </div>
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-check-circle text-blue-600"></i>
                </div>
            </div>
        </div>

        <!-- Aktivitas Terbaru -->
        <div class="bg-white rounded-lg shadow-sm border p-4 hover:shadow-md transition-shadow cursor-pointer" onclick="toggleActivityModal()">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-600">Aktivitas Terbaru</p>
                    <p class="text-xl font-bold text-gray-800">Lihat Detail</p>
                </div>
                <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-history text-purple-600"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Total Peminjaman Modal -->
    <div id="totalModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div class="flex items-center justify-between p-4 border-b">
                <h3 class="text-lg font-semibold text-gray-800">Total Peminjaman</h3>
                <button onclick="toggleTotalModal()" class="p-1 hover:bg-gray-100 rounded">
                    <i class="fas fa-times text-gray-500"></i>
                </button>
            </div>
            
            <div class="p-4 overflow-y-auto max-h-96">
                <?php
                // Get all transactions
                $total_stmt = $conn->prepare("
                    SELECT st.*, st.tanggal_transaksi, st.status, st.status_peminjaman, st.reservation_number,
                           st.tanggal_pengembalian
                    FROM stock_transactions st
                    WHERE st.borrower_id = ?
                    ORDER BY st.tanggal_transaksi DESC
                ");
                $total_stmt->bind_param("i", $borrower_id);
                $total_stmt->execute();
                $total_result = $total_stmt->get_result();
                ?>
                
                <?php if ($total_result->num_rows > 0): ?>
                    <div class="space-y-3">
                        <?php while ($transaction = $total_result->fetch_assoc()): ?>
                            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                                <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                                    <i class="fas fa-file-alt text-green-600 text-sm"></i>
                                </div>
                                <div class="flex-1">
                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($transaction['reservation_number']); ?></p>
                                    <p class="text-xs text-gray-500">
                                        <?php echo date('d M Y, H:i', strtotime($transaction['tanggal_transaksi'])); ?>
                                        <?php if ($transaction['tanggal_pengembalian']): ?>
                                            - Dikembalikan: <?php echo date('d M Y', strtotime($transaction['tanggal_pengembalian'])); ?>
                                        <?php endif; ?>
                                    </p>
                                </div>
                                <span class="px-2 py-1 rounded text-xs font-medium <?php 
                                    echo $transaction['status_peminjaman'] == 'Dipinjam' ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-800'; 
                                ?>">
                                    <?php echo $transaction['status_peminjaman'] == 'Dipinjam' ? 'Dipinjam' : 'Selesai'; ?>
                                </span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8">
                        <i class="fas fa-inbox text-gray-400 text-3xl mb-2"></i>
                        <p class="text-gray-500">Belum ada peminjaman</p>
                    </div>
                <?php endif; ?>
                
                <?php $total_stmt->close(); ?>
            </div>
        </div>
    </div>

    <!-- Sedang Dipinjam Modal -->
    <div id="sedangModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div class="flex items-center justify-between p-4 border-b">
                <h3 class="text-lg font-semibold text-gray-800">Sedang Dipinjam</h3>
                <button onclick="toggleSedangModal()" class="p-1 hover:bg-gray-100 rounded">
                    <i class="fas fa-times text-gray-500"></i>
                </button>
            </div>
            
            <div class="p-4 overflow-y-auto max-h-96">
                <?php
                // Get currently borrowed items
                $sedang_stmt = $conn->prepare("
                    SELECT st.*, st.tanggal_transaksi, st.status, st.status_peminjaman, st.reservation_number
                    FROM stock_transactions st
                    WHERE st.borrower_id = ? AND st.status_peminjaman = 'Dipinjam'
                    ORDER BY st.tanggal_transaksi DESC
                ");
                $sedang_stmt->bind_param("i", $borrower_id);
                $sedang_stmt->execute();
                $sedang_result = $sedang_stmt->get_result();
                ?>
                
                <?php if ($sedang_result->num_rows > 0): ?>
                    <div class="space-y-3">
                        <?php while ($transaction = $sedang_result->fetch_assoc()): ?>
                            <div class="flex items-center p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                                <div class="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center mr-3">
                                    <i class="fas fa-clock text-yellow-600 text-sm"></i>
                                </div>
                                <div class="flex-1">
                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($transaction['reservation_number']); ?></p>
                                    <p class="text-xs text-gray-500">
                                        Dipinjam: <?php echo date('d M Y, H:i', strtotime($transaction['tanggal_transaksi'])); ?>
                                    </p>
                                </div>
                                <span class="px-2 py-1 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
                                    Sedang Dipinjam
                                </span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8">
                        <i class="fas fa-check-circle text-gray-400 text-3xl mb-2"></i>
                        <p class="text-gray-500">Tidak ada item yang sedang dipinjam</p>
                    </div>
                <?php endif; ?>
                
                <?php $sedang_stmt->close(); ?>
            </div>
        </div>
    </div>

    <!-- Selesai Dipinjam Modal -->
    <div id="selesaiModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div class="flex items-center justify-between p-4 border-b">
                <h3 class="text-lg font-semibold text-gray-800">Selesai Dipinjam</h3>
                <button onclick="toggleSelesaiModal()" class="p-1 hover:bg-gray-100 rounded">
                    <i class="fas fa-times text-gray-500"></i>
                </button>
            </div>
            
            <div class="p-4 overflow-y-auto max-h-96">
                <?php
                // Get completed transactions
                $selesai_stmt = $conn->prepare("
                    SELECT st.*, st.tanggal_transaksi, st.status, st.status_peminjaman, st.reservation_number,
                           st.tanggal_pengembalian
                    FROM stock_transactions st
                    WHERE st.borrower_id = ? AND st.status_peminjaman = 'Dikembalikan'
                    ORDER BY st.tanggal_pengembalian DESC
                ");
                $selesai_stmt->bind_param("i", $borrower_id);
                $selesai_stmt->execute();
                $selesai_result = $selesai_stmt->get_result();
                ?>
                
                <?php if ($selesai_result->num_rows > 0): ?>
                    <div class="space-y-3">
                        <?php while ($transaction = $selesai_result->fetch_assoc()): ?>
                            <div class="flex items-center p-3 bg-green-50 rounded-lg border border-green-200">
                                <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                                    <i class="fas fa-check-circle text-green-600 text-sm"></i>
                                </div>
                                <div class="flex-1">
                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($transaction['reservation_number']); ?></p>
                                    <p class="text-xs text-gray-500">
                                        Dipinjam: <?php echo date('d M Y', strtotime($transaction['tanggal_transaksi'])); ?> - 
                                        Dikembalikan: <?php echo date('d M Y', strtotime($transaction['tanggal_pengembalian'])); ?>
                                    </p>
                                </div>
                                <span class="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
                                    Selesai
                                </span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8">
                        <i class="fas fa-history text-gray-400 text-3xl mb-2"></i>
                        <p class="text-gray-500">Belum ada peminjaman yang selesai</p>
                    </div>
                <?php endif; ?>
                
                <?php $selesai_stmt->close(); ?>
            </div>
        </div>
    </div>

    <!-- Activity Modal -->
    <div id="activityModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div class="flex items-center justify-between p-4 border-b">
                <h3 class="text-lg font-semibold text-gray-800">Aktivitas Terbaru</h3>
                <button onclick="toggleActivityModal()" class="p-1 hover:bg-gray-100 rounded">
                    <i class="fas fa-times text-gray-500"></i>
                </button>
            </div>
            
            <div class="p-4 overflow-y-auto max-h-96">
                <?php
                // Get recent transactions for modal
                $recent_stmt = $conn->prepare("
                    SELECT st.*, st.tanggal_transaksi, st.status, st.status_peminjaman, st.reservation_number
                    FROM stock_transactions st
                    WHERE st.borrower_id = ?
                    ORDER BY st.tanggal_transaksi DESC
                    LIMIT 10
                ");
                $recent_stmt->bind_param("i", $borrower_id);
                $recent_stmt->execute();
                $recent_result = $recent_stmt->get_result();
                ?>
                
                <?php if ($recent_result->num_rows > 0): ?>
                    <div class="space-y-3">
                        <?php while ($transaction = $recent_result->fetch_assoc()): ?>
                            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                                <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center mr-3">
                                    <i class="fas fa-file-alt text-purple-600 text-sm"></i>
                                </div>
                                <div class="flex-1">
                                    <p class="font-medium text-gray-800 text-sm"><?php echo htmlspecialchars($transaction['reservation_number']); ?></p>
                                    <p class="text-xs text-gray-500">
                                        <?php echo date('d M Y, H:i', strtotime($transaction['tanggal_transaksi'])); ?>
                                    </p>
                                </div>
                                <span class="px-2 py-1 rounded text-xs font-medium <?php 
                                    echo $transaction['status_peminjaman'] == 'Dipinjam' ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-800'; 
                                ?>">
                                    <?php echo $transaction['status_peminjaman'] == 'Dipinjam' ? 'Dipinjam' : 'Selesai'; ?>
                                </span>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-8">
                        <i class="fas fa-inbox text-gray-400 text-3xl mb-2"></i>
                        <p class="text-gray-500">Belum ada aktivitas peminjaman</p>
                    </div>
                <?php endif; ?>
                
                <?php $recent_stmt->close(); ?>
            </div>
        </div>
    </div>
</main>

<script>
    function toggleActivityModal() {
        const modal = document.getElementById('activityModal');
        modal.classList.toggle('hidden');
    }

    function toggleTotalModal() {
        const modal = document.getElementById('totalModal');
        modal.classList.toggle('hidden');
    }

    function toggleSedangModal() {
        const modal = document.getElementById('sedangModal');
        modal.classList.toggle('hidden');
    }

    function toggleSelesaiModal() {
        const modal = document.getElementById('selesaiModal');
        modal.classList.toggle('hidden');
    }

    // Close modal when clicking outside
    ['activityModal', 'totalModal', 'sedangModal', 'selesaiModal'].forEach(modalId => {
        document.getElementById(modalId).addEventListener('click', function(e) {
            if (e.target === this) {
                document.getElementById(modalId).classList.add('hidden');
            }
        });
    });

    // Close modal with Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            ['activityModal', 'totalModal', 'sedangModal', 'selesaiModal'].forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (!modal.classList.contains('hidden')) {
                    modal.classList.add('hidden');
                }
            });
        }
    });
</script>

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