<?php
$page_title = 'ERP Dashboard';
require_once('includes/load.php');
page_require_level(4);

// Get dashboard data
$products_count = count_by_id('products');
$out_of_stock_count = find_by_sql("SELECT COUNT(*) AS count FROM products WHERE quantity <= 0");
$low_stock_count = find_by_sql("SELECT COUNT(*) AS count FROM products WHERE quantity > 0 AND quantity < 10");
$total_inventory_value = find_by_sql("SELECT SUM(quantity * buy_price) AS value FROM products")[0]['value'];

// Get stock alerts
$low_stock_products = find_by_sql("SELECT part_number, name, quantity FROM products WHERE quantity < 10 ORDER BY quantity ASC LIMIT 5");

// Get recent transactions
$latest_transactions = find_by_sql("SELECT sm.part_number, p.name, sm.movement_type, sm.quantity_changed, sm.movement_date
                                     FROM stock_movement sm
                                     JOIN products p ON sm.part_number = p.part_number
                                     ORDER BY sm.movement_date DESC LIMIT 5");

// Stock movement data (30 days) - MODIFIED TO BE BASED ON VALUE
$stock_movement = find_by_sql("SELECT 
                                     DATE_FORMAT(sm.movement_date, '%Y-%m-%d') AS day,
                                     SUM(CASE WHEN sm.movement_type = 'inbound' THEN sm.quantity_changed * p.buy_price ELSE 0 END) AS inbound_value,
                                     SUM(CASE WHEN sm.movement_type != 'inbound' THEN sm.quantity_changed * p.buy_price ELSE 0 END) AS outbound_value
                                     FROM stock_movement sm
                                     JOIN products p ON sm.part_number = p.part_number
                                     WHERE sm.movement_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                                     GROUP BY day
                                     ORDER BY day ASC");

// Format for charts
$movement_dates = [];
$inbound_data = [];
$outbound_data = [];
foreach ($stock_movement as $row) {
    $movement_dates[] = date('M j', strtotime($row['day']));
    $inbound_data[] = $row['inbound_value'];
    $outbound_data[] = $row['outbound_value'];
}

// Top products by stock value
$top_products = find_by_sql("SELECT part_number, name, quantity, buy_price 
                                 FROM products 
                                 ORDER BY (quantity * buy_price) DESC 
                                 LIMIT 5");
?>

<?php include_once('layouts/header.php'); ?>

<div class="dashboard-container">
    <div class="dashboard-header">
        <h1><i class="fas fa-tachometer-alt"></i> PT KANAKA PINASTHIKA SENTOSA</h1>
        <div class="header-actions">
            <button class="btn-refresh"><i class="fas fa-sync-alt"></i> Refresh</button>
        </div>
    </div>

    <div class="summary-cards">
        <div class="summary-card card-total">
            <div class="card-icon">
                <i class="fas fa-boxes"></i>
            </div>
            <div class="card-content">
                <h3>Total Products</h3>
                <h2><?php echo (int)$products_count['total']; ?></h2>
            </div>
        </div>

        <div class="summary-card card-value">
            <div class="card-icon">
                <i class="fas fa-dollar-sign"></i>
            </div>
            <div class="card-content">
                <h3>Inventory Value</h3>
                <h2>Rp<?php echo number_format($total_inventory_value, 0); ?></h2>
            </div>
        </div>

        <div class="summary-card card-warning">
            <div class="card-icon">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="card-content">
                <h3>Low Stock</h3>
                <h2><?php echo (int)$low_stock_count[0]['count']; ?></h2>
            </div>
        </div>

        <div class="summary-card card-danger">
            <div class="card-icon">
                <i class="fas fa-times-circle"></i>
            </div>
            <div class="card-content">
                <h3>Out of Stock</h3>
                <h2><?php echo (int)$out_of_stock_count[0]['count']; ?></h2>
            </div>
        </div>
    </div>

    <div class="dashboard-content">
        <div class="content-left">
            <div class="dashboard-card">
                <div class="card-header">
                    <h3><i class="fas fa-chart-line"></i> Stock Movement (30 Days)</h3>
                    <div class="chart-legend">
                        <span class="legend-inbound"><i class="fas fa-square"></i> Inbound Value</span>
                        <span class="legend-outbound"><i class="fas fa-square"></i> Outbound Value</span>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="movementChart" height="300"></canvas>
                </div>
            </div>

            <div class="dashboard-card">
                <div class="card-header">
                    <h3><i class="fas fa-exchange-alt"></i> Recent Transactions</h3>
                    <a href="all_transaction" class="view-all">View All</a>
                </div>
                <div class="card-body">
                    <div class="transactions-table">
                        <table>
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Part No.</th>
                                    <th>Type</th>
                                    <th class="text-right">Qty</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($latest_transactions as $txn): ?>
                                <tr>
                                    <td><?php echo date('M j, H:i', strtotime($txn['movement_date'])); ?></td>
                                    <td><?php echo $txn['part_number']; ?></td>
                                    <td>
                                        <?php 
                                        $badge_class = '';
                                        switch($txn['movement_type']) {
                                            case 'inbound': $badge_class = 'success'; break;
                                            case 'outbound': $badge_class = 'danger'; break;
                                            case 'transfer': $badge_class = 'info'; break;
                                            default: $badge_class = 'secondary';
                                        }
                                        ?>
                                        <span class="badge badge-<?php echo $badge_class; ?>">
                                            <?php echo ucfirst($txn['movement_type']); ?>
                                        </span>
                                    </td>
                                    <td class="text-right"><?php echo (int)$txn['quantity_changed']; ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="content-right">
            <div class="dashboard-card">
                <div class="card-header alert-header">
                    <h3><i class="fas fa-bell"></i> Stock Alerts</h3>
                    <span class="alert-count"><?php echo (int)$low_stock_count[0]['count']; ?> alerts</span>
                </div>
                <div class="card-body">
                    <div class="alerts-list">
                        <?php if (count($low_stock_products) > 0): ?>
                            <?php foreach ($low_stock_products as $product): ?>
                            <div class="alert-item">
                                <div class="alert-icon">
                                    <i class="fas fa-exclamation-circle"></i>
                                </div>
                                <div class="alert-content">
                                    <h4><?php echo $product['name']; ?></h4>
                                    <p><?php echo $product['part_number']; ?></p>
                                </div>
                                <div class="alert-value">
                                    <span class="stock-value"><?php echo (int)$product['quantity']; ?></span>
                                    <small>in stock</small>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="no-alerts">
                                <i class="fas fa-check-circle"></i>
                                <p>No stock alerts</p>
                            </div>
                        <?php endif; ?>
                    </div>
                    <a href="low_stock.php" class="btn-view-all">View All Alerts</a>
                </div>
            </div>

            <div class="dashboard-card">
                <div class="card-header">
                    <h3><i class="fas fa-star"></i> Top Products by Value</h3>
                </div>
                <div class="card-body">
                    <div class="top-products">
                        <?php foreach ($top_products as $product): ?>
                        <div class="product-item">
                            <div class="product-info">
                                <h4><?php echo $product['name']; ?></h4>
                                <p><?php echo $product['part_number']; ?></p>
                            </div>
                            <div class="product-value">
                                <span>Rp<?php echo number_format($product['quantity'] * $product['buy_price'], 0); ?></span>
                                <small><?php echo (int)$product['quantity']; ?> units</small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Modern Dashboard Styles */
:root {
    --primary: #4361ee;
    --secondary: #3f37c9;
    --success: #4cc9f0;
    --danger: #f72585;
    --warning: #f8961e;
    --info: #4895ef;
    --light: #f8f9fa;
    --dark: #212529;
    --gray: #6c757d;
    --light-gray: #e9ecef;
}

.dashboard-container {
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: #333;
}

.dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
}

.dashboard-header h1 {
    font-size: 28px;
    font-weight: 600;
    color: var(--dark);
    margin: 0;
}

.dashboard-header h1 i {
    margin-right: 10px;
    color: var(--primary);
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 15px;
}


.btn-refresh {
    background: var(--light);
    border: 1px solid var(--light-gray);
    padding: 8px 15px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
}

.btn-refresh:hover {
    background: #e9ecef;
}

.btn-refresh i {
    margin-right: 5px;
}

.summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.summary-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    transition: transform 0.3s, box-shadow 0.3s;
}

.summary-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.card-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 24px;
    color: white;
}

.card-total .card-icon { background: var(--primary); }
.card-value .card-icon { background: var(--success); }
.card-warning .card-icon { background: var(--warning); }
.card-danger .card-icon { background: var(--danger); }

.card-content h3 {
    font-size: 14px;
    color: var(--gray);
    margin: 0 0 5px 0;
    font-weight: 500;
}

.card-content h2 {
    font-size: 24px;
    margin: 0;
    font-weight: 600;
}

.dashboard-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 25px;
}

.dashboard-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    margin-bottom: 25px;
    overflow: hidden;
}

.card-header {
    padding: 15px 20px;
    border-bottom: 1px solid var(--light-gray);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    font-size: 16px;
    margin: 0;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.card-header h3 i {
    margin-right: 10px;
    color: var(--primary);
}

.alert-header h3 i { color: var(--warning); }

.chart-legend {
    display: flex;
    gap: 15px;
    font-size: 13px;
}

.legend-inbound i { color: var(--success); }
.legend-outbound i { color: var(--danger); }

.view-all {
    font-size: 13px;
    color: var(--primary);
    text-decoration: none;
    font-weight: 500;
}

.card-body {
    padding: 20px;
}

.transactions-table {
    width: 100%;
    overflow-x: auto;
}

.transactions-table table {
    width: 100%;
    border-collapse: collapse;
}

.transactions-table th {
    text-align: left;
    padding: 8px 10px;
    font-size: 13px;
    color: var(--gray);
    text-transform: uppercase;
    font-weight: 500;
    background: var(--light);
}

.transactions-table td {
    padding: 12px 10px;
    border-bottom: 1px solid var(--light-gray);
    font-size: 14px;
}

.transactions-table tr:last-child td {
    border-bottom: none;
}

.text-right { text-align: right; }

.badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    color: white;
}

.badge-success { background: var(--success); }
.badge-danger { background: var(--danger); }
.badge-info { background: var(--info); }
.badge-secondary { background: var(--gray); }

.alert-count {
    background: var(--warning);
    color: white;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.alerts-list {
    margin-bottom: 15px;
}

.alert-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--light-gray);
}

.alert-item:last-child {
    border-bottom: none;
}

.alert-icon {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: rgba(248, 150, 30, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    color: var(--warning);
    font-size: 16px;
}

.alert-content h4 {
    margin: 0 0 2px 0;
    font-size: 14px;
    font-weight: 500;
}

.alert-content p {
    margin: 0;
    font-size: 12px;
    color: var(--gray);
}

.alert-value {
    margin-left: auto;
    text-align: right;
}

.stock-value {
    font-size: 16px;
    font-weight: 600;
    color: var(--warning);
    display: block;
}

.alert-value small {
    font-size: 11px;
    color: var(--gray);
}

.no-alerts {
    text-align: center;
    padding: 30px 0;
    color: var(--success);
}

.no-alerts i {
    font-size: 40px;
    margin-bottom: 10px;
}

.no-alerts p {
    margin: 0;
    font-size: 14px;
}

.btn-view-all {
    display: block;
    text-align: center;
    padding: 10px;
    background: var(--light);
    color: var(--primary);
    text-decoration: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    transition: background 0.3s;
}

.btn-view-all:hover {
    background: #e9ecef;
}

.top-products {
    margin-top: 10px;
}

.product-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--light-gray);
}

.product-item:last-child {
    border-bottom: none;
}

.product-info h4 {
    margin: 0 0 2px 0;
    font-size: 14px;
    font-weight: 500;
}

.product-info p {
    margin: 0;
    font-size: 12px;
    color: var(--gray);
}

.product-value {
    margin-left: auto;
    text-align: right;
}

.product-value span {
    font-size: 15px;
    font-weight: 600;
    color: var(--dark);
    display: block;
}

.product-value small {
    font-size: 11px;
    color: var(--gray);
}

@media (max-width: 1200px) {
    .dashboard-content {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .summary-cards {
        grid-template-columns: 1fr 1fr;
    }
    
    .dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}

@media (max-width: 576px) {
    .summary-cards {
        grid-template-columns: 1fr;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Stock Movement Chart
const movementCtx = document.getElementById('movementChart').getContext('2d');
const movementChart = new Chart(movementCtx, {
    type: 'bar',
    data: {
        labels: <?php echo json_encode($movement_dates); ?>,
        datasets: [
            {
                label: 'Inbound Value',
                data: <?php echo json_encode($inbound_data); ?>,
                backgroundColor: 'rgba(76, 201, 240, 0.7)',
                borderColor: 'rgba(76, 201, 240, 1)',
                borderWidth: 1,
                borderRadius: 4
            },
            {
                label: 'Outbound Value',
                data: <?php echo json_encode($outbound_data); ?>,
                backgroundColor: 'rgba(247, 37, 133, 0.7)',
                borderColor: 'rgba(247, 37, 133, 1)',
                borderWidth: 1,
                borderRadius: 4
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': Rp' + parseInt(context.raw);
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    drawBorder: false
                },
                ticks: {
                    callback: function(value) {
                        return 'Rp' + parseInt(value);
                    }
                }
            },
            x: {
                grid: {
                    display: false
                }
            }
        },
        interaction: {
            intersect: false,
            mode: 'index'
        }
    }
});

// Refresh button functionality
document.querySelector('.btn-refresh').addEventListener('click', function() {
    location.reload();
});
</script>

<?php include_once('layouts/footer.php'); ?>