<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Trenutni mesec i godina
$current_month = date('m');
$current_year = date('Y');

// Period za izveštaj (podrazumevano tekući mesec)
$report_month = isset($_GET['month']) ? intval($_GET['month']) : $current_month;
$report_year = isset($_GET['year']) ? intval($_GET['year']) : $current_year;

// Validacija vrednosti
if ($report_month < 1 || $report_month > 12) {
    $report_month = $current_month;
}

if ($report_year < 2000 || $report_year > date('Y') + 1) {
    $report_year = $current_year;
}

// Prvi i poslednji dan meseca
$first_day = sprintf('%04d-%02d-01', $report_year, $report_month);
$last_day = date('Y-m-t', strtotime($first_day));

// Dohvatanje statistike za izabrani mesec
$monthly_stats = [
    'total_orders' => get_row("SELECT COUNT(*) as count FROM orders WHERE created_at BETWEEN ? AND ?", [$first_day, $last_day . ' 23:59:59'])['count'],
    'completed_orders' => get_row("SELECT COUNT(*) as count FROM orders WHERE status IN ('delivered', 'shipped') AND created_at BETWEEN ? AND ?", [$first_day, $last_day . ' 23:59:59'])['count'],
    'cancelled_orders' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'canceled' AND created_at BETWEEN ? AND ?", [$first_day, $last_day . ' 23:59:59'])['count'],
    'total_sales' => get_row("SELECT SUM(total) as total FROM orders WHERE created_at BETWEEN ? AND ?", [$first_day, $last_day . ' 23:59:59'])['total'] ?: 0,
    'completed_sales' => get_row("SELECT SUM(total) as total FROM orders WHERE status IN ('delivered', 'shipped') AND created_at BETWEEN ? AND ?", [$first_day, $last_day . ' 23:59:59'])['total'] ?: 0,
    'avg_order_value' => 0
];

// Prosečna vrednost porudžbine
if ($monthly_stats['total_orders'] > 0) {
    $monthly_stats['avg_order_value'] = $monthly_stats['total_sales'] / $monthly_stats['total_orders'];
}

// Dnevna statistika za grafikon
$daily_stats = get_rows("
    SELECT DATE(created_at) as date, 
           COUNT(*) as order_count, 
           SUM(total) as sales_total 
    FROM orders 
    WHERE created_at BETWEEN ? AND ? 
    GROUP BY DATE(created_at) 
    ORDER BY date ASC
", [$first_day, $last_day . ' 23:59:59']);

// Najprodavaniji proizvodi za izabrani mesec
$top_products = get_rows("
    SELECT p.id, p.name, p.sku, SUM(oi.quantity) as quantity, SUM(oi.quantity * oi.price) as total
    FROM order_items oi
    JOIN orders o ON oi.order_id = o.id
    JOIN products p ON oi.product_id = p.id
    WHERE o.created_at BETWEEN ? AND ?
    GROUP BY p.id
    ORDER BY quantity DESC
    LIMIT 10
", [$first_day, $last_day . ' 23:59:59']);

// Statistika po statusima
$status_stats = get_rows("
    SELECT status, COUNT(*) as count, SUM(total) as total
    FROM orders
    WHERE created_at BETWEEN ? AND ?
    GROUP BY status
", [$first_day, $last_day . ' 23:59:59']);

// Format za prikazivanje meseca
$month_name = date('F Y', strtotime($first_day));

// Naslov stranice
$page_title = 'Izveštaji - ' . $month_name;

// Uključivanje header-a
require_once '../includes/header.php';
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Izveštaji</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Kontrolna tabla</a></li>
                    <li class="breadcrumb-item active">Izveštaji</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <!-- Period selector -->
        <div class="card mb-4">
            <div class="card-header">
                <h3 class="card-title">Izaberite period</h3>
            </div>
            <div class="card-body">
                <form method="get" class="form-inline">
                    <div class="form-group mr-3">
                        <label for="month" class="mr-2">Mesec:</label>
                        <select name="month" id="month" class="form-control">
                            <?php for ($m = 1; $m <= 12; $m++): ?>
                                <option value="<?php echo $m; ?>" <?php echo $m == $report_month ? 'selected' : ''; ?>>
                                    <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="form-group mr-3">
                        <label for="year" class="mr-2">Godina:</label>
                        <select name="year" id="year" class="form-control">
                            <?php for ($y = $current_year - 3; $y <= $current_year + 1; $y++): ?>
                                <option value="<?php echo $y; ?>" <?php echo $y == $report_year ? 'selected' : ''; ?>>
                                    <?php echo $y; ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Prikaži</button>
                </form>
            </div>
        </div>
        
        <!-- Monthly summary -->
        <div class="row">
            <div class="col-md-3 col-sm-6 col-12">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-shopping-cart"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ukupno porudžbina</span>
                        <span class="info-box-number"><?php echo $monthly_stats['total_orders']; ?></span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-12">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-check"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Realizovane porudžbine</span>
                        <span class="info-box-number"><?php echo $monthly_stats['completed_orders']; ?></span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-12">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-times"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Otkazane porudžbine</span>
                        <span class="info-box-number"><?php echo $monthly_stats['cancelled_orders']; ?></span>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-12">
                <div class="info-box">
                    <span class="info-box-icon bg-warning"><i class="fas fa-calculator"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Prosečna vrednost</span>
                        <span class="info-box-number"><?php echo format_price($monthly_stats['avg_order_value']); ?></span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="info-box">
                    <span class="info-box-icon bg-primary"><i class="fas fa-money-bill-wave"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ukupna prodaja</span>
                        <span class="info-box-number"><?php echo format_price($monthly_stats['total_sales']); ?></span>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-money-bill-wave"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Realizovana prodaja</span>
                        <span class="info-box-number"><?php echo format_price($monthly_stats['completed_sales']); ?></span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sales Chart -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Prodaja po danima - <?php echo $month_name; ?></h3>
            </div>
            <div class="card-body">
                <div class="chart">
                    <canvas id="salesChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
                </div>
            </div>
        </div>
        
        <div class="row">
            <!-- Top Products -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Najprodavaniji proizvodi</h3>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Proizvod</th>
                                    <th>SKU</th>
                                    <th class="text-right">Količina</th>
                                    <th class="text-right">Vrednost</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($top_products)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center">Nema podataka za prikazani period</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($top_products as $product): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                                            <td><?php echo $product['sku']; ?></td>
                                            <td class="text-right"><?php echo $product['quantity']; ?></td>
                                            <td class="text-right"><?php echo format_price($product['total']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Order Status Stats -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Statistika po statusima</h3>
                    </div>
                    <div class="card-body">
                        <canvas id="statusChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Export Options -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Izvoz izveštaja</h3>
            </div>
            <div class="card-body">
                <div class="btn-group">
                    <a href="/admin/reports/export.php?type=orders&month=<?php echo $report_month; ?>&year=<?php echo $report_year; ?>&format=csv" class="btn btn-outline-secondary">
                        <i class="fas fa-file-csv"></i> Izvezi porudžbine (CSV)
                    </a>
                    <a href="/admin/reports/export.php?type=products&month=<?php echo $report_month; ?>&year=<?php echo $report_year; ?>&format=csv" class="btn btn-outline-secondary">
                        <i class="fas fa-file-csv"></i> Izvezi prodaju proizvoda (CSV)
                    </a>
                    <a href="/admin/reports/export.php?type=sales&month=<?php echo $report_month; ?>&year=<?php echo $report_year; ?>&format=csv" class="btn btn-outline-secondary">
                        <i class="fas fa-file-csv"></i> Izvezi dnevnu prodaju (CSV)
                    </a>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- ChartJS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Podaci za grafikon prodaje po danima
    var salesData = {
        labels: [
            <?php
            foreach ($daily_stats as $day) {
                echo "'" . date('d.m', strtotime($day['date'])) . "', ";
            }
            ?>
        ],
        datasets: [{
            label: 'Ukupna prodaja',
            backgroundColor: 'rgba(60,141,188,0.2)',
            borderColor: 'rgba(60,141,188,1)',
            pointRadius: 3,
            pointColor: '#3b8bba',
            pointStrokeColor: 'rgba(60,141,188,1)',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(60,141,188,1)',
            data: [
                <?php
                foreach ($daily_stats as $day) {
                    echo $day['sales_total'] . ", ";
                }
                ?>
            ]
        }, {
            label: 'Broj porudžbina',
            backgroundColor: 'rgba(210, 214, 222, 0.2)',
            borderColor: 'rgba(210, 214, 222, 1)',
            pointRadius: 3,
            pointColor: 'rgba(210, 214, 222, 1)',
            pointStrokeColor: '#c1c7d1',
            pointHighlightFill: '#fff',
            pointHighlightStroke: 'rgba(220,220,220,1)',
            data: [
                <?php
                foreach ($daily_stats as $day) {
                    echo $day['order_count'] . ", ";
                }
                ?>
            ]
        }]
    };

    // Podaci za grafikon statusa porudžbina
    var statusData = {
        labels: [
            <?php
            foreach ($status_stats as $status) {
                echo "'" . get_order_status_name($status['status']) . "', ";
            }
            ?>
        ],
        datasets: [{
            data: [
                <?php
                foreach ($status_stats as $status) {
                    echo $status['count'] . ", ";
                }
                ?>
            ],
            backgroundColor: [
                '#f56954', '#00a65a', '#f39c12', '#00c0ef', '#3c8dbc', '#d2d6de'
            ]
        }]
    };

    // Grafikon prodaje po danima
    var salesChartCanvas = document.getElementById('salesChart').getContext('2d');
    new Chart(salesChartCanvas, {
        type: 'line',
        data: salesData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Grafikon statusa porudžbina
    var statusChartCanvas = document.getElementById('statusChart').getContext('2d');
    new Chart(statusChartCanvas, {
        type: 'doughnut',
        data: statusData,
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
});
</script>

<?php require_once '../includes/footer.php'; ?>