<?php
// Set header untuk memberitahu browser bahwa ini adalah response JSON
header('Content-Type: application/json');

// Error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Koneksi Database
    include_once '../data.php';
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");

    // Default range tanggal: bulan ini
    $start_date = date('Y-m-01');
    $end_date = date('Y-m-t');

    // Ambil input dari request POST (yang dikirim oleh JavaScript)
    $input = json_decode(file_get_contents('php://input'), true);

    if ($input && isset($input['start_date']) && isset($input['end_date'])) {
        $start_date = filter_var($input['start_date'], FILTER_SANITIZE_STRING);
        $end_date = filter_var($input['end_date'], FILTER_SANITIZE_STRING);
        $selected_cabang = isset($input['cabang']) ? filter_var($input['cabang'], FILTER_SANITIZE_STRING) : '';
    } else {
        // Fallback jika tidak ada input (misalnya diakses langsung)
        $selected_cabang = '';
    }

    // Ambil daftar cabang untuk filter
    $cabang_query = "SELECT kode, nama FROM cabang ORDER BY nama ASC";
    $cabang_result = $conn->query($cabang_query);
    $cabang_list = [];
    while ($row = $cabang_result->fetch_assoc()) {
        $cabang_list[] = $row;
    }

    $is_global_view = empty($selected_cabang);

    // =================================================================== //
    // BAGIAN QUERY YANG HILANG SEBELUMNYA DIMULAI DARI SINI
    // =================================================================== //
    
    // Query untuk data ringkasan (penjualan)
    if ($is_global_view) {
        // Data global (semua cabang)
        $summary_sql = "
        SELECT 
            j.cab, cabang.nama AS cabang_nama,
            SUM(CAST(p.netto 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.netto 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
        LEFT JOIN cabang ON j.cab = cabang.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY j.cab, cabang.nama
        ORDER BY total_penjualan DESC
        ";
        
        $stmt = $conn->prepare($summary_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
        $stmt->execute();
        $summary_result = $stmt->get_result();
        
        $summary_data = [];
        while ($row = $summary_result->fetch_assoc()) {
            $summary_data[] = $row;
        }
        $stmt->close();
        
        // Hitung total keseluruhan
        $total_keseluruhan = 0;
        $total_transaksi_keseluruhan = 0;
        $total_quantity_keseluruhan = 0;
        foreach ($summary_data as $data) {
            $total_keseluruhan += $data['total_penjualan'];
            $total_transaksi_keseluruhan += $data['total_transaksi'];
            $total_quantity_keseluruhan += $data['total_quantity'];
        }
        
        $view_title = "Dashboard Penjualan Global";
        $cabang_info = "Semua Cabang";
        
    } else {
        // Data per cabang
        $cabang_info_query = "SELECT nama FROM cabang WHERE kode = ?";
        $stmt = $conn->prepare($cabang_info_query);
        $stmt->bind_param("s", $selected_cabang);
        $stmt->execute();
        $cabang_info_result = $stmt->get_result();
        
        if ($cabang_info_result && $cabang_info_result->num_rows > 0) {
            $cabang_info_row = $cabang_info_result->fetch_assoc();
            $cabang_info = $cabang_info_row['nama'];
        } else {
            $cabang_info = "Cabang " . $selected_cabang;
        }
        $stmt->close();
        
        $summary_sql = "
        SELECT 
            SUM(CAST(p.netto 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.netto 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 = ? AND p.payment < '01'
        ";
        
        $stmt = $conn->prepare($summary_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
        $stmt->execute();
        $summary_result = $stmt->get_result();
        
        if ($summary_result && $summary_result->num_rows > 0) {
            $summary_data = [$summary_result->fetch_assoc()];
        } else {
            $summary_data = [['total_penjualan' => 0, 'total_quantity' => 0, 'total_transaksi' => 0, 'avg_transaksi' => 0, 'total_diskon' => 0, 'total_ppn' => 0, 'total_service' => 0]];
        }
        $stmt->close();
        
        $total_keseluruhan = $summary_data[0]['total_penjualan'];
        $total_transaksi_keseluruhan = $summary_data[0]['total_transaksi'];
        $total_quantity_keseluruhan = $summary_data[0]['total_quantity'];
        
        $view_title = "Dashboard Penjualan: " . $cabang_info;
    }
    
    // Query untuk data per hari (untuk grafik tren) - penjualan
    if ($is_global_view) {
        $tren_sql = "
        SELECT 
            j.tanggal,
            SUM(CAST(p.netto 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 p.payment < '01'
        GROUP BY j.tanggal
        ORDER BY j.tanggal ASC
        ";
        $stmt = $conn->prepare($tren_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $tren_sql = "
        SELECT 
            j.tanggal,
            SUM(CAST(p.netto 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 = ? AND p.payment < '01'
        GROUP BY j.tanggal
        ORDER BY j.tanggal ASC
        ";
        $stmt = $conn->prepare($tren_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    $stmt->execute();
    $tren_result = $stmt->get_result();
    $tren_data = [];
    while ($row = $tren_result->fetch_assoc()) {
        $tren_data[] = $row;
    }
    $stmt->close();

    // Query untuk data per produk (top 10) - penjualan
    if ($is_global_view) {
        $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.netto 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 p.payment < '01'
        GROUP BY p.kode, p.name, p.group_name
        ORDER BY total_quantity DESC
        LIMIT 10
        ";
        $stmt = $conn->prepare($produk_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $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.netto 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 = ? AND p.payment < '01'
        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, $selected_cabang);
    }
    $stmt->execute();
    $produk_result = $stmt->get_result();
    $produk_data = [];
    while ($row = $produk_result->fetch_assoc()) {
        $produk_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per tipe transaksi - penjualan
    if ($is_global_view) {
        $tipe_sql = "
        SELECT 
            tt.nama AS tipe_transaksi,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment < '01'
        GROUP BY tt.nama
        ORDER BY total_transaksi DESC
        ";
        $stmt = $conn->prepare($tipe_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $tipe_sql = "
        SELECT 
            tt.nama AS tipe_transaksi,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto AS DECIMAL(15,2))) as total_penjualan
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND j.cab = ? AND p.payment < '01'
        GROUP BY tt.nama
        ORDER BY total_transaksi DESC
        ";
        $stmt = $conn->prepare($tipe_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    $stmt->execute();
    $tipe_result = $stmt->get_result();
    $tipe_data = [];
    while ($row = $tipe_result->fetch_assoc()) {
        $tipe_data[] = $row;
    }
    $stmt->close();
    
    // Hitung total untuk tipe transaksi
    $total_tipe_transaksi = 0;
    $total_tipe_penjualan = 0;
    foreach ($tipe_data as $data) {
        $total_tipe_transaksi += $data['total_transaksi'];
        $total_tipe_penjualan += $data['total_penjualan'];
    }

    // Query untuk data metode pembayaran
    if ($is_global_view) {
        $payment_sql = "
        SELECT 
            p.name,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.harga AS DECIMAL(15,2))) as total_penjualan,
            AVG(CAST(p.harga AS DECIMAL(15,2))) as avg_transaksi
        FROM jual j
        LEFT JOIN pesani p ON j.nomor = p.nomor
        WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 AND p.payment > '01' AND p.harga > 0
        GROUP BY p.name
        ORDER BY total_penjualan DESC
        ";
        $stmt = $conn->prepare($payment_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $payment_sql = "
        SELECT 
            p.name,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.harga AS DECIMAL(15,2))) as total_penjualan,
            AVG(CAST(p.harga AS DECIMAL(15,2))) as avg_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 = ? AND p.payment > '01' AND p.harga > 0
        GROUP BY p.name
        ORDER BY total_penjualan DESC
        ";
        $stmt = $conn->prepare($payment_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    $stmt->execute();
    $payment_result = $stmt->get_result();
    $payment_data = [];
    while ($row = $payment_result->fetch_assoc()) {
        $payment_data[] = $row;
    }
    $stmt->close();

    // Hitung total untuk metode pembayaran
    $total_payment_transaksi = 0;
    $total_payment_penjualan = 0;
    foreach ($payment_data as $data) {
        $total_payment_transaksi += $data['total_transaksi'];
        $total_payment_penjualan += $data['total_penjualan'];
    }
    $total_payment_avg = $total_payment_transaksi > 0 ? $total_payment_penjualan / $total_payment_transaksi : 0;

    // Query untuk data per kasir (hanya untuk view per cabang)
    if (!$is_global_view) {
        $kasir_sql = "
        SELECT 
            u.nama AS kasir_nama,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto 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 = ? AND p.payment < '01'
        GROUP BY u.nama
        ORDER BY total_transaksi DESC
        ";
        $stmt = $conn->prepare($kasir_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
        $stmt->execute();
        $kasir_result = $stmt->get_result();
        $kasir_data = [];
        while ($row = $kasir_result->fetch_assoc()) {
            $kasir_data[] = $row;
        }
        $stmt->close();
        
        $total_kasir_transaksi = 0;
        $total_kasir_penjualan = 0;
        foreach ($kasir_data as $data) {
            $total_kasir_transaksi += $data['total_transaksi'];
            $total_kasir_penjualan += $data['total_penjualan'];
        }
        $total_kasir_avg = $total_kasir_transaksi > 0 ? $total_kasir_penjualan / $total_kasir_transaksi : 0;
    } else {
        $kasir_data = [];
        $total_kasir_transaksi = 0;
        $total_kasir_penjualan = 0;
        $total_kasir_avg = 0;
    }

    // Query untuk data per kategori produk
    if ($is_global_view) {
        $kategori_sql = "
        SELECT 
            p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto 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 p.payment < '01'
        GROUP BY p.group_name
        ORDER BY total_penjualan DESC
        ";
        $stmt = $conn->prepare($kategori_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $kategori_sql = "
        SELECT 
            p.group_name,
            SUM(CAST(p.quantity AS DECIMAL(10,2))) as total_quantity,
            SUM(CAST(p.netto 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 = ? AND p.payment < '01'
        GROUP BY p.group_name
        ORDER BY total_penjualan DESC
        ";
        $stmt = $conn->prepare($kategori_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    $stmt->execute();
    $kategori_result = $stmt->get_result();
    $kategori_data = [];
    while ($row = $kategori_result->fetch_assoc()) {
        $kategori_data[] = $row;
    }
    $stmt->close();
    
    // Query untuk data per hari dalam seminggu
    if ($is_global_view) {
        $hari_sql = "
        SELECT 
            DAYNAME(j.tanggal) as hari,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto 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 p.payment < '01'
        GROUP BY DAYNAME(j.tanggal)
        ORDER BY CASE DAYNAME(j.tanggal) WHEN 'Monday' THEN 1 WHEN 'Tuesday' THEN 2 WHEN 'Wednesday' THEN 3 WHEN 'Thursday' THEN 4 WHEN 'Friday' THEN 5 WHEN 'Saturday' THEN 6 WHEN 'Sunday' THEN 7 END
        ";
        $stmt = $conn->prepare($hari_sql);
        $stmt->bind_param("ss", $start_date, $end_date);
    } else {
        $hari_sql = "
        SELECT 
            DAYNAME(j.tanggal) as hari,
            COUNT(DISTINCT j.nomor) as total_transaksi,
            SUM(CAST(p.netto 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 = ? AND p.payment < '01'
        GROUP BY DAYNAME(j.tanggal)
        ORDER BY CASE DAYNAME(j.tanggal) WHEN 'Monday' THEN 1 WHEN 'Tuesday' THEN 2 WHEN 'Wednesday' THEN 3 WHEN 'Thursday' THEN 4 WHEN 'Friday' THEN 5 WHEN 'Saturday' THEN 6 WHEN 'Sunday' THEN 7 END
        ";
        $stmt = $conn->prepare($hari_sql);
        $stmt->bind_param("sss", $start_date, $end_date, $selected_cabang);
    }
    $stmt->execute();
    $hari_result = $stmt->get_result();
    $hari_data = [];
    while ($row = $hari_result->fetch_assoc()) {
        $hari_data[] = $row;
    }
    $stmt->close();

    // =================================================================== //
    // BAGIAN QUERY BERAKHIR DI SINI
    // =================================================================== //

    $conn->close();

    // Gabungkan semua data ke dalam satu array untuk dijadikan response JSON
    echo json_encode([
        'success' => true,
        'view_title' => $view_title,
        'cabang_info' => $cabang_info,
        'cabang_list' => $cabang_list,
        'summary_data' => $summary_data,
        'tren_data' => $tren_data,
        'produk_data' => $produk_data,
        'tipe_data' => $tipe_data,
        'payment_data' => $payment_data,
        'kasir_data' => $kasir_data,
        'kategori_data' => $kategori_data,
        'hari_data' => $hari_data,
        'totals' => [
            'total_keseluruhan' => $total_keseluruhan,
            'total_transaksi_keseluruhan' => $total_transaksi_keseluruhan,
            'total_quantity_keseluruhan' => $total_quantity_keseluruhan,
            'total_tipe_transaksi' => $total_tipe_transaksi,
            'total_tipe_penjualan' => $total_tipe_penjualan,
            'total_payment_transaksi' => $total_payment_transaksi,
            'total_payment_penjualan' => $total_payment_penjualan,
            'total_payment_avg' => $total_payment_avg,
            'total_kasir_transaksi' => $total_kasir_transaksi,
            'total_kasir_penjualan' => $total_kasir_penjualan,
            'total_kasir_avg' => $total_kasir_avg
        ],
        'is_global_view' => $is_global_view
    ]);

} catch (Exception $e) {
    // Jika terjadi error, kirim response JSON dengan pesan error
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error_message' => $e->getMessage()
    ]);
}
?>