{% extends 'base.html' %}

{% block title %}Dashboard - Manufacturing App{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page header -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">
            <i class="bi bi-speedometer2 me-2"></i>
            Dashboard
        </h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <div class="btn-group me-2">
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="exportDashboard()">
                    <i class="bi bi-download me-1"></i>Export
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="printDashboard()">
                    <i class="bi bi-printer me-1"></i>Print
                </button>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-white-50 text-uppercase mb-1">
                                Daily Production
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-white">
                                {{ daily_production.total_quantity|default:"0" }}
                            </div>
                            <div class="text-white-50">
                                {{ daily_production.total_orders|default:"0" }} orders
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="bi bi-tools fa-2x text-white-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card success h-100">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-white-50 text-uppercase mb-1">
                                Daily Sales
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-white">
                                Rp {{ daily_sales.total_amount|default:"0"|floatformat:0 }}
                            </div>
                            <div class="text-white-50">
                                {{ daily_sales.total_orders|default:"0" }} orders
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="bi bi-cart-check fa-2x text-white-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card warning h-100">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-white-50 text-uppercase mb-1">
                                Daily Purchases
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-white">
                                Rp {{ daily_purchases.total_amount|default:"0"|floatformat:0 }}
                            </div>
                            <div class="text-white-50">
                                {{ daily_purchases.total_orders|default:"0" }} orders
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="bi bi-cart-plus fa-2x text-white-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card info h-100">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-white-50 text-uppercase mb-1">
                                Monthly Profit
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-white">
                                Rp {{ monthly_profit|default:"0"|floatformat:0 }}
                            </div>
                            <div class="text-white-50">
                                This month
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="bi bi-graph-up fa-2x text-white-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-xl-8 col-lg-7">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Production Overview</h6>
                </div>
                <div class="card-body">
                    <canvas id="productionChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>

        <div class="col-xl-4 col-lg-5">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Inventory Status</h6>
                </div>
                <div class="card-body">
                    <canvas id="inventoryChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Activities and Alerts -->
    <div class="row">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Manufacturing Orders</h6>
                </div>
                <div class="card-body">
                    {% if recent_manufacturing %}
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Order</th>
                                        <th>Product</th>
                                        <th>Quantity</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for order in recent_manufacturing %}
                                    <tr>
                                        <td>{{ order.order_number }}</td>
                                        <td>{{ order.product.name }}</td>
                                        <td>{{ order.quantity }}</td>
                                        <td>{{ order.date }}</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <p class="text-muted">No recent manufacturing orders.</p>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Low Stock Alerts</h6>
                </div>
                <div class="card-body">
                    {% if low_stock_products %}
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Current Stock</th>
                                        <th>Min Level</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for product in low_stock_products %}
                                    <tr>
                                        <td>{{ product.name }}</td>
                                        <td>{{ product.current_stock }}</td>
                                        <td>{{ product.min_stock_level }}</td>
                                        <td>
                                            <span class="badge bg-danger">Low Stock</span>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <p class="text-muted">All products have sufficient stock.</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Weekly and Monthly Summary -->
    <div class="row mt-4">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Weekly Summary</h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-6">
                            <h4 class="text-primary">{{ weekly_production.total_quantity|default:"0" }}</h4>
                            <p class="text-muted">Production</p>
                        </div>
                        <div class="col-6">
                            <h4 class="text-success">Rp {{ weekly_sales.total_amount|default:"0"|floatformat:0 }}</h4>
                            <p class="text-muted">Sales</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">Monthly Summary</h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-6">
                            <h4 class="text-primary">{{ monthly_production.total_quantity|default:"0" }}</h4>
                            <p class="text-muted">Production</p>
                        </div>
                        <div class="col-6">
                            <h4 class="text-success">Rp {{ monthly_sales.total_amount|default:"0"|floatformat:0 }}</h4>
                            <p class="text-muted">Sales</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Production Chart
const productionCtx = document.getElementById('productionChart').getContext('2d');
const productionChart = new Chart(productionCtx, {
    type: 'line',
    data: {
        labels: ['Daily', 'Weekly', 'Monthly'],
        datasets: [{
            label: 'Production',
            data: [
                {{ daily_production.total_quantity|default:"0" }},
                {{ weekly_production.total_quantity|default:"0" }},
                {{ monthly_production.total_quantity|default:"0" }}
            ],
            borderColor: 'rgb(75, 192, 192)',
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            tension: 0.1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Inventory Chart
const inventoryCtx = document.getElementById('inventoryChart').getContext('2d');
const inventoryChart = new Chart(inventoryCtx, {
    type: 'doughnut',
    data: {
        labels: ['Low Stock', 'Normal', 'Overstocked'],
        datasets: [{
            data: [
                {{ low_stock_products|length }},
                10,
                5
            ],
            backgroundColor: [
                '#dc3545',
                '#28a745',
                '#ffc107'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});

// Print Dashboard Function
function printDashboard() {
    window.print();
}

// Export Dashboard Function
function exportDashboard() {
    // Create CSV content
    const csvContent = [
        ['Dashboard Report', ''],
        ['Generated on', new Date().toLocaleString('id-ID')],
        [''],
        ['Daily Statistics', ''],
        ['Daily Production', '{{ daily_production.total_quantity|default:"0" }}'],
        ['Daily Sales', '${{ daily_sales.total_amount|default:"0" }}'],
        ['Daily Purchases', '${{ daily_purchases.total_amount|default:"0" }}'],
        [''],
        ['Weekly Statistics', ''],
        ['Weekly Production', '{{ weekly_production.total_quantity|default:"0" }}'],
        ['Weekly Sales', '${{ weekly_sales.total_amount|default:"0" }}'],
        ['Weekly Purchases', '${{ weekly_purchases.total_amount|default:"0" }}'],
        [''],
        ['Monthly Statistics', ''],
        ['Monthly Production', '{{ monthly_production.total_quantity|default:"0" }}'],
        ['Monthly Sales', '${{ monthly_sales.total_amount|default:"0" }}'],
        ['Monthly Purchases', '${{ monthly_purchases.total_amount|default:"0" }}']
    ].map(row => row.join(',')).join('\n');
    
    // Create and download file
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'dashboard_report.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
{% endblock %}
