<?php
// Konfigurasi Database
// $host = 'localhost';
// $user = 'root';
// $pass = '';
// $db   = 'pos_m';

// Set header ke JSON
header('Content-Type: application/json');

// Ambil parameter dari request
$branch = $_GET['branch'] ?? '';
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

try {
    // Koneksi ke database
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);    
    
    if ($conn->connect_error) {
        throw new Exception("Koneksi gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");
    
    // Query untuk data ringkasan cabang
    $summary_sql = "
    SELECT 
        SUM(CAST(p.jumlah AS DECIMAL(15,2))) as total_penjualan,
        SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
        COUNT(DISTINCT j.nomor) as total_transaksi,
        AVG(CAST(p.jumlah AS DECIMAL(15,2))) as avg_transaksi,
        SUM(CAST(p.discr AS DECIMAL(15,2))) as total_diskon,
        SUM(CAST(p.ppn AS DECIMAL(15,2))) as total_ppn,
        SUM(CAST(p.service AS DECIMAL(15,2))) as total_service
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ?
    ";
    
    $stmt = $conn->prepare($summary_sql);
    $stmt->bind_param("sss", $start_date, $end_date, $branch);
    $stmt->execute();
    $summary_result = $stmt->get_result();
    $summary_data = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // Query untuk data tren harian cabang
    $tren_sql = "
    SELECT 
        j.tanggal,
        SUM(CAST(p.jumlah AS DECIMAL(15,2))) as total_penjualan,
        COUNT(DISTINCT j.nomor) as total_transaksi
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ?
    GROUP BY j.tanggal
    ORDER BY j.tanggal ASC
    ";
    
    $stmt = $conn->prepare($tren_sql);
    $stmt->bind_param("sss", $start_date, $end_date, $branch);
    $stmt->execute();
    $tren_result = $stmt->get_result();
    
    $tren_data = [
        'labels' => [],
        'data' => []
    ];
    
    while ($row = $tren_result->fetch_assoc()) {
        $tren_data['labels'][] = $row['tanggal'];
        $tren_data['data'][] = $row['total_penjualan'];
    }
    $stmt->close();
    
    // Query untuk data produk terlaris cabang
    $produk_sql = "
    SELECT 
        p.kode, p.name AS nama_barang, p.group_name,
        SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
        SUM(CAST(p.jumlah AS DECIMAL(15,2))) as total_penjualan
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ?
    GROUP BY p.kode, p.name, p.group_name
    ORDER BY total_quantity DESC
    LIMIT 10
    ";
    
    $stmt = $conn->prepare($produk_sql);
    $stmt->bind_param("sss", $start_date, $end_date, $branch);
    $stmt->execute();
    $produk_result = $stmt->get_result();
    
    $produk_data = [
        'labels' => [],
        'data' => []
    ];
    
    while ($row = $produk_result->fetch_assoc()) {
        $produk_data['labels'][] = $row['nama_barang'];
        $produk_data['data'][] = $row['total_quantity'];
    }
    $stmt->close();
    
    // Query untuk data per kasir
    $kasir_sql = "
    SELECT 
        u.nama AS kasir_nama,
        COUNT(DISTINCT j.nomor) as total_transaksi,
        SUM(CAST(p.jumlah AS DECIMAL(15,2))) as total_penjualan
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    LEFT JOIN users u ON j.kasir = u.kode
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ?
    GROUP BY u.nama
    ORDER BY total_transaksi DESC
    ";
    
    $stmt = $conn->prepare($kasir_sql);
    $stmt->bind_param("sss", $start_date, $end_date, $branch);
    $stmt->execute();
    $kasir_result = $stmt->get_result();
    
    $kasir_data = [];
    while ($row = $kasir_result->fetch_assoc()) {
        $kasir_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per jam
    $jam_sql = "
    SELECT 
        j.jamm,
        COUNT(DISTINCT j.nomor) as total_transaksi,
        SUM(CAST(p.jumlah AS DECIMAL(15,2))) as total_penjualan
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ?
    GROUP BY j.jamm
    ORDER BY j.jamm ASC
    ";
    
    $stmt = $conn->prepare($jam_sql);
    $stmt->bind_param("sss", $start_date, $end_date, $branch);
    $stmt->execute();
    $jam_result = $stmt->get_result();
    
    $jam_data = [
        'labels' => [],
        'data' => []
    ];
    
    while ($row = $jam_result->fetch_assoc()) {
        $jam_data['labels'][] = $row['jamm'] . ':00';
        $jam_data['data'][] = $row['total_transaksi'];
    }
    $stmt->close();
    
    // Generate HTML for the branch content
    ob_start();
    ?>
    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card stat-card primary">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label">Total Penjualan</div>
                        <div class="stat-value">Rp <?= number_format($summary_data['total_penjualan'], 0, ',', '.') ?></div>
                    </div>
                    <div class="stat-icon text-primary">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card success">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label">Total Transaksi</div>
                        <div class="stat-value"><?= number_format($summary_data['total_transaksi'], 0, ',', '.') ?></div>
                    </div>
                    <div class="stat-icon text-success">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card warning">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label">Rata-rata Transaksi</div>
                        <div class="stat-value">Rp <?= number_format($summary_data['total_transaksi'] > 0 ? $summary_data['total_penjualan'] / $summary_data['total_transaksi'] : 0, 0, ',', '.') ?></div>
                    </div>
                    <div class="stat-icon text-warning">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stat-card info">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label">Total Qty</div>
                        <div class="stat-value"><?= number_format($summary_data['total_quantity'], 0, ',', '.') ?></div>
                    </div>
                    <div class="stat-icon text-info">
                        <i class="fas fa-boxes"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-chart-line me-2"></i>Tren Penjualan Harian
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="branch-sales-trend-<?= $branch ?>"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-clock me-2"></i>Distribusi Transaksi per Jam
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="branch-hourly-<?= $branch ?>"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tables Row -->
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-user me-2"></i>Performa Kasir
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Kasir</th>
                                    <th class="text-end">Transaksi</th>
                                    <th class="text-end">Total Penjualan</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($kasir_data as $data): ?>
                                    <tr>
                                        <td><?= $data['kasir_nama'] ?></td>
                                        <td class="text-end"><?= number_format($data['total_transaksi'], 0, ',', '.') ?></td>
                                        <td class="text-end">Rp <?= number_format($data['total_penjualan'], 0, ',', '.') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-box me-2"></i>Produk Terlaris
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="branch-product-<?= $branch ?>"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
    $html = ob_get_clean();
    
    // Return JSON response
    echo json_encode([
        'success' => true,
        'html' => $html,
        'charts' => [
            'tren' => $tren_data,
            'produk' => $produk_data,
            'jam' => $jam_data
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>