<?php

namespace App\Controllers;

use App\Models\SaleModel;
use App\Models\SaleDetailModel;
use App\Models\ProductInModel;
use App\Models\ProductOutModel;
use App\Models\UserModel;
use App\Models\GudangModel;



class Report extends BaseController
{
    protected $saleModel;
    protected $saleDetailModel;
    protected $productInModel;
    protected $productOutModel;

    public function __construct()
    {

        $session = session();
    if (!$session->get('logged_in') || $session->get('role') !== 'superadmin') {
        redirect()->to(base_url('admin/dashboard'))->send();
        exit;
    }
        $this->saleModel       = new SaleModel();
        $this->saleDetailModel = new SaleDetailModel();
        $this->productInModel  = new ProductInModel();
        $this->productOutModel = new ProductOutModel();
        $this->userModel       = new UserModel();
    }

    public function sales()
{
    $saleModel = new \App\Models\SaleModel();
    $userModel = new \App\Models\UserModel(); // untuk pilihan filter kasir

    $startDate = $this->request->getGet('start_date');
    $endDate   = $this->request->getGet('end_date');
    $userId    = $this->request->getGet('user_id');

    $filters = [
        'start_date' => $startDate,
        'end_date'   => $endDate,
        'user_id'    => $userId
    ];

    $page     = (int) ($this->request->getGet('page') ?? 1);
    $perPage  = 10;
    $offset   = ($page - 1) * $perPage;

    // Ambil data paginated
    $sales = $saleModel->getJoinAll($filters, $perPage, $offset);

    // Total baris untuk filter (tanpa limit)
    $totalRows = count($saleModel->getJoinAll($filters));

    // Pagination info
    $pager = [
        'currentPage' => $page,
        'totalPages'  => max(1, ceil($totalRows / $perPage)),
        'perPage'     => $perPage,
        'totalRows'   => $totalRows,
    ];

    $data['sales'] = $sales; // hanya yang sesuai halaman
    $data['users'] = $userModel->findAll();
    $data['pager'] = $pager;

    // Ringkasan total item dan total harga
    $db = \Config\Database::connect();
    $builder = $db->table('sales');
    $builder->select('SUM(sale_detail.qty) AS total_item, SUM(sales.total) AS total_harga');
    $builder->join('sale_detail', 'sale_detail.sale_id = sales.id', 'left');

    if ($startDate && $endDate) {
        $builder->where('DATE(sales.tanggal) >=', $startDate);
        $builder->where('DATE(sales.tanggal) <=', $endDate);
    }

    if ($userId) {
        $builder->where('sales.user_id', $userId);
    }

    $data['ringkasan'] = $builder->get()->getRow();

    return view('reports/sales', $data);
}

public function delete()
{
    $ids = $this->request->getPost('ids');
    if (is_array($ids)) {
        foreach ($ids as $id) {
            // Hapus data dari tabel sales
            $this->salesModel->delete($id);
        }
        return redirect()->back()->with('success', 'Data berhasil dihapus.');
    }
    return redirect()->back()->with('error', 'Tidak ada data yang dipilih.');
}


public function edit($id)
{
    $saleModel = new \App\Models\SaleModel();
    $customerModel = new \App\Models\CustomerModel();
    $userModel = new \App\Models\UserModel();
    $saleDetailModel = new \App\Models\SaleDetailModel();
    $itemModel = new \App\Models\ItemModel();
    $taxModel = new \App\Models\TaxModel();
    $activeTax = $taxModel->where('aktif', 1)->first();


    $data['tax'] = $activeTax;
    $data['sales'] = $saleModel->getJoinById($id);
    $data['customers'] = $customerModel->findAll();
    $data['users'] = $userModel->findAll();
    $data['details'] = $saleDetailModel->getDetailBySale($id);
    $data['items'] = $itemModel->findAll();

    return view('reports/edit', $data);
}

public function update($id)
{
    $items = $this->request->getPost('items');
    $saleModel = new \App\Models\SaleModel();
    $saleDetailModel = new \App\Models\SaleDetailModel();

    // Update data utama
    $data = [
        'customer_id'    => $this->request->getPost('customer_id') ?: null,
        'jenis_pesan'    => $this->request->getPost('jenis_pesan'),
        'no_meja'        => $this->request->getPost('no_meja'),
        'total'          => $this->request->getPost('total'),
        'pajak_persen'   => $this->request->getPost('pajak_persen'),
        'pajak_nominal'  => $this->request->getPost('pajak_nominal'),
        'total_bayar'    => $this->request->getPost('grand_total'),
        'dibayar'        => $this->request->getPost('dibayar'),
        'kembalian'      => $this->request->getPost('kembalian')
    ];
    $saleModel->update($id, $data);

    $existingIds = [];

    foreach ($items as $item) {
        if (!empty($item['id'])) {
            // Update item lama
            $saleDetailModel->update($item['id'], [
                'item_id'  => $item['item_id'],
                'qty'      => $item['qty'],
                'harga'    => $item['harga'],
                'subtotal' => $item['subtotal']
            ]);
            $existingIds[] = $item['id'];
        } else {
            // Tambah item baru
            $saleDetailModel->insert([
                'sale_id'  => $id,
                'item_id'  => $item['item_id'],
                'qty'      => $item['qty'],
                'harga'    => $item['harga'],
                'subtotal' => $item['subtotal']
            ]);
        }
    }

    // Hapus item yang tidak ada dalam POST
    $allDetails = $saleDetailModel->where('sale_id', $id)->findAll();
    foreach ($allDetails as $detail) {
        if (!in_array($detail['id'], $existingIds)) {
            $saleDetailModel->delete($detail['id']);
        }
    }

    return redirect()->to(base_url('admin/report/sales'))->with('success', 'Transaksi berhasil diperbarui.');
}

public function summary()
{
    $db = \Config\Database::connect();

    // Ambil parameter tanggal dari GET
    $start_date = $this->request->getGet('start_date');
    $end_date   = $this->request->getGet('end_date');

    $builder = $db->table('sales');
    $builder->select("
        COALESCE(customers.nama, '-') AS customer_name,

        -- TAKE AWAY - CASH
        SUM(CASE 
            WHEN sales.jenis_pesan = 'take_away' AND sales.payment_method = 'cash' THEN sales.total_bayar
            ELSE 0
        END) AS takeaway_cash_total,

        SUM(CASE 
            WHEN sales.jenis_pesan = 'take_away' AND sales.payment_method = 'cash' THEN sale_detail.qty
            ELSE 0
        END) AS takeaway_cash_qty,

        -- TAKE AWAY - TRANSFER
        SUM(CASE 
            WHEN sales.jenis_pesan = 'take_away' AND sales.payment_method = 'transfer' THEN sales.total_bayar
            ELSE 0
        END) AS takeaway_transfer_total,

        SUM(CASE 
            WHEN sales.jenis_pesan = 'take_away' AND sales.payment_method = 'transfer' THEN sale_detail.qty
            ELSE 0
        END) AS takeaway_transfer_qty,

        -- DINE IN - CASH
        SUM(CASE 
            WHEN sales.jenis_pesan = 'dine_in' AND sales.payment_method = 'cash' THEN sales.total_bayar
            ELSE 0
        END) AS dinein_cash_total,

        SUM(CASE 
            WHEN sales.jenis_pesan = 'dine_in' AND sales.payment_method = 'cash' THEN sale_detail.qty
            ELSE 0
        END) AS dinein_cash_qty,

        -- DINE IN - TRANSFER
        SUM(CASE 
            WHEN sales.jenis_pesan = 'dine_in' AND sales.payment_method = 'transfer' THEN sales.total_bayar
            ELSE 0
        END) AS dinein_transfer_total,

        SUM(CASE 
            WHEN sales.jenis_pesan = 'dine_in' AND sales.payment_method = 'transfer' THEN sale_detail.qty
            ELSE 0
        END) AS dinein_transfer_qty
    ");
    $builder->join('customers', 'customers.id = sales.customer_id', 'left');
    $builder->join('sale_detail', 'sale_detail.sale_id = sales.id', 'left');

    // Tambahkan filter tanggal jika tersedia
    if ($start_date && $end_date) {
        $builder->where('DATE(sales.tanggal) >=', $start_date);
        $builder->where('DATE(sales.tanggal) <=', $end_date);
    }

    $builder->groupBy('sales.customer_id');
    $query = $builder->get();

    $data['summary'] = $query->getResultArray();

    // Hitung grand total semua pembelian
    $data['grand_total'] = array_reduce($data['summary'], function ($carry, $row) {
        return $carry + $row['takeaway_cash_total'] + $row['takeaway_transfer_total'] +
                        $row['dinein_cash_total'] + $row['dinein_transfer_total'];
    }, 0);

    // Hitung grand total qty
    $data['grand_qty'] = array_reduce($data['summary'], function ($carry, $row) {
        return $carry + $row['takeaway_cash_qty'] + $row['takeaway_transfer_qty'] +
                        $row['dinein_cash_qty'] + $row['dinein_transfer_qty'];
    }, 0);

    // Kirim juga tanggal ke view agar tetap tampil di input
    $data['start_date'] = $start_date;
    $data['end_date'] = $end_date;

    return view('reports/summary', $data);
}








public function salesUpdate($id)
{
    $data = [
        'jenis_pesan' => $this->request->getPost('jenis_pesan'),
        'no_meja' => $this->request->getPost('no_meja'),
        'customer_id' => $this->request->getPost('customer_id') ?: null,
    ];

    $this->saleModel->update($id, $data);
    return redirect()->to(base_url('report/sales'))->with('success', 'Transaksi berhasil diperbarui.');
}


    public function product_in()
    {
        $data = [
            'title' => 'Laporan Barang Masuk',
            'product_in' => $this->productInModel->getJoinAll()
        ];
        return view('reports/product_in', $data);
    }

    public function product_out()
{
    $data = [
        'title' => 'Laporan Barang Keluar',
        'product_out' => $this->productOutModel->getJoinAll()
    ];
    return view('reports/product_out', $data);
}

public function productOutDetail($id)
{
    $model = new ProductOutModel();
    $detailModel = new ProductOutDetailModel();
    $itemModel = new ItemModel();
    $warehouseModel = new GudangModel();

    $data['out'] = $model->find($id);
    $data['details'] = $model->getDetailsByProductOutId($id)
        ->select('product_out_detail.*, items.nama AS nama_item, gudang.nama AS nama_gudang')
        ->join('items', 'items.id = product_out_detail.item_id', 'left')
        ->join('gudang', 'gudang.id = product_out_detail.gudang_id', 'left')
        ->where('product_out_id', $id)
        ->findAll();

    return $this->response->setJSON($data); // Untuk modal detail (AJAX)
}

public function productOutEdit($id)
{
    $model = new ProductOutModel();
    $detailModel = new ProductOutDetailModel();
    $itemModel = new ItemModel();
    $warehouseModel = new GudangModel();

    $data['out'] = $model->find($id);
    $data['details'] = $detailModel
        ->where('product_out_id', $id)
        ->findAll();
    $data['items'] = $itemModel->findAll();
    $data['warehouses'] = $warehouseModel->findAll();

    return $this->response->setJSON($data); // Untuk modal edit (AJAX)
}

public function productOutUpdate($id)
{
    $model = new ProductOutModel();
    $detailModel = new ProductOutDetailModel();

    // Update data utama
    $model->update($id, [
        'tanggal_keluar' => $this->request->getPost('tanggal_keluar'),
        'note' => $this->request->getPost('note'),
    ]);

    // Hapus detail lama
    $detailModel->where('product_out_id', $id)->delete();

    // Simpan detail baru dari input
    $items = $this->request->getPost('item_id');
    $qtys = $this->request->getPost('qty');
    $gudangs = $this->request->getPost('gudang_id');

    foreach ($items as $i => $item_id) {
        $detailModel->insert([
            'product_out_id' => $id,
            'item_id' => $item_id,
            'qty' => $qtys[$i],
            'gudang_id' => $gudangs[$i],
        ]);
    }

    return $this->response->setJSON(['status' => 'success', 'message' => 'Data berhasil diperbarui']);
}

public function productOutDelete($id)
{
    $model = new ProductOutModel();
    $detailModel = new ProductOutDetailModel();

    // Hapus detail terlebih dahulu
    $detailModel->where('product_out_id', $id)->delete();

    // Lalu hapus data utama
    $model->delete($id);

    return $this->response->setJSON(['status' => 'success', 'message' => 'Data berhasil dihapus']);
}


public function updateByKode($kode)
{
    $model = new \App\Models\ProductOutModel();

    $entries = $model->getDetailByKode($kode);
    if (!$entries) {
        return redirect()->to('/report/product_out')->with('error', 'Data tidak ditemukan.');
    }

    $tanggal_keluar = $this->request->getPost('tanggal_keluar');
    $keterangan     = $this->request->getPost('keterangan');
    $item_ids       = $this->request->getPost('item_id');    // array
    $gudang_ids     = $this->request->getPost('gudang_id');  // array

    foreach ($entries as $i => $entry) {
        $model->update($entry['id'], [
            'tanggal_keluar' => $tanggal_keluar,
            'keterangan'     => $keterangan,
            'item_id'        => $item_ids[$i] ?? $entry['item_id'],
            'gudang_id'      => $gudang_ids[$i] ?? $entry['gudang_id'],
        ]);
    }

    return redirect()->to('/report/product_out')->with('success', 'Data berhasil diperbarui.');
}


public function deleteByKode($kode)
{
    $model = new \App\Models\ProductOutModel();

    $entries = $model->getDetailByKode($kode);
    if (!$entries) {
        return redirect()->to('/report/product_out')->with('error', 'Data tidak ditemukan.');
    }

    foreach ($entries as $entry) {
        $model->delete($entry['id']);
    }

    return redirect()->to('/report/product_out')->with('success', 'Data berhasil dihapus.');
}

public function update_by_kode($kode)
{
    $productOutModel = new \App\Models\ProductOutModel();

    $dataUmum = [
        'user_id' => session('user_id'),
        'updated_at' => date('Y-m-d H:i:s'),
    ];

    // ambil detail dari POST
    $details = $this->request->getPost('detail');

    if (!$details || !is_array($details)) {
        return redirect()->back()->with('error', 'Data detail tidak valid.');
    }

    // hapus semua data lama dengan kode tersebut
    $productOutModel->where('kode', $kode)->delete();

    // masukkan ulang data detail
    foreach ($details as $d) {
        $productOutModel->insert([
            'kode'      => $kode,
            'item_id'   => $d['item_id'],
            'gudang_id' => $d['gudang_id'],
            'qty'       => $d['qty'],
            'keterangan'=> $d['keterangan'] ?? null,
            'user_id'   => $dataUmum['user_id'],
            'created_at'=> $dataUmum['updated_at']
        ]);
    }

    return redirect()->to('/report/product_out')->with('success', 'Data berhasil diperbarui.');
}

public function delete_by_kode($kode)
{
    $productOutModel = new \App\Models\ProductOutModel();
    $productOutModel->where('kode', $kode)->delete();

    return redirect()->to('/report/product_out')->with('success', 'Data berhasil dihapus.');
}

public function detail_all()
{
    $model = new \App\Models\ProductOutModel();
    $data['productout_all'] = $model->getJoinAll(); // ambil semua tanpa group

    return view('reports/product_out_detail', $data);
}



public function items()
{
    $db       = \Config\Database::connect();
    $request  = \Config\Services::request();

    $isAjax = $request->isAJAX();
    $search   = $request->getGet('q');
    $page     = (int) ($request->getGet('page') ?? 1);
    $perPage  = 10;
    $offset   = ($page - 1) * $perPage;

    $builder = $db->table('sale_detail');
    $builder->select('items.barcode, items.nama, SUM(sale_detail.qty) as total_qty, SUM(sale_detail.subtotal) as total_harga');
    $builder->join('items', 'items.id = sale_detail.item_id');

    if ($search) {
        $builder->groupStart()
            ->like('items.nama', $search)
            ->orLike('items.barcode', $search)
            ->groupEnd();
    }

    $builder->groupBy('items.id');
    $builder->orderBy('total_qty', 'DESC');

    // Jalankan query dan ambil semua hasil (tanpa limit)
    $allResults = $builder->get()->getResultArray();
    $total      = count($allResults);

    // Ambil data sesuai halaman
    $items = array_slice($allResults, $offset, $perPage);

    // Pagination info seperti di sales()
    $pager = [
        'currentPage' => $page,
        'totalPages'  => max(1, ceil($total / $perPage)),
        'perPage'     => $perPage,
        'totalRows'   => $total,
    ];

    return view('reports/items', [
        'title'  => 'Laporan Penjualan per Item',
        'items'  => $items,
        'search' => $search,
        'pager'  => $pager,
        'offset' => $offset
    ]);
}








}
