<?php

namespace App\Controllers;

use App\Models\SaleModel;
use App\Models\SaleDetailModel;
use App\Models\CustomerModel;
use App\Models\ItemModel;
use App\Models\SettingModel;
use App\Models\TaxModel;
use CodeIgniter\Controller;

class Sale extends Controller
{
    protected $saleModel;
    protected $detailModel;
    protected $customerModel;
    protected $itemModel;
    protected $taxModel;
    protected $saleDetailModel;

    public function __construct()
    {
        $this->saleModel        = new SaleModel();
        $this->detailModel      = new SaleDetailModel();
        $this->customerModel    = new CustomerModel();
        $this->itemModel        = new ItemModel();
        $this->taxModel         = new TaxModel();
        $this->saleDetailModel  = new SaleDetailModel();
    }

    public function create()
    {
        $tax = $this->taxModel->where('aktif', 1)->first();

        $data = [
            'title'            => 'Transaksi Penjualan',
            'customers'        => $this->customerModel->findAll(),
            'items'            => $this->itemModel->where('is_active', 1)->findAll(),
            'print_sale_id'    => session()->getFlashdata('print_sale_id'),
            'activeTax'        => $tax ? true : false,
            'activeTaxPercent' => $tax['persen'] ?? 0,
        ];

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


  public function save()
{
    $db = \Config\Database::connect();
    $db->transStart();

    try {
        $kode           = 'TRX' . date('YmdHis');
        $tanggal        = date('Y-m-d H:i:s');
        $user_id        = session()->get('user_id');

        // Ambil data dari form
        $subtotal       = (int) $this->request->getPost('subtotal');
        $diskonPersen   = (float) $this->request->getPost('diskon_persen');
        $diskonNominal  = (int) $this->request->getPost('diskon_nominal');
        $taxNominal     = (int) $this->request->getPost('pajak_nominal');
        $totalBayar     = (int) $this->request->getPost('total_final');
        $dibayar        = (int) $this->request->getPost('paid');
        $payment_method = $this->request->getPost('payment_method');

        // Customer
        $customer_id     = $this->request->getPost('customer_id') ?: null;
        $customer_manual = trim($this->request->getPost('customer_manual'));
        if (empty($customer_id) && $customer_manual !== '') {
            $existing = $this->customerModel->where('nama', $customer_manual)->first();
            $customer_id = $existing ? $existing['id'] : $this->customerModel->insert([
                'nama'       => $customer_manual,
                'created_at' => $tanggal
            ]);
        }

        // Jenis Pesan & Pajak
        $jenis_pesan = $this->request->getPost('jenis_pesan');
        $no_meja     = $jenis_pesan === 'dine_in' ? $this->request->getPost('no_meja') : null;
        $tax         = $this->taxModel->where('aktif', 1)->first();
        $taxPercent  = $tax ? (float) $tax['persen'] : 0;
        $kembalian   = $dibayar - $totalBayar;

        if ($dibayar < $totalBayar) {
            return redirect()->back()->withInput()->with('error', 'Nominal pembayaran kurang dari total.');
        }

        // Simpan ke `sales`
        $this->saleModel->save([
            'kode'           => $kode,
            'tanggal'        => $tanggal,
            'customer_id'    => $customer_id,
            'payment_method' => $payment_method,
            'total'          => $subtotal,
            'diskon_persen'  => $diskonPersen,
            'diskon_nominal' => $diskonNominal,
            'pajak_persen'   => $taxPercent,
            'pajak_nominal'  => $taxNominal,
            'total_bayar'    => $totalBayar,
            'dibayar'        => $dibayar,
            'kembalian'      => $kembalian,
            'user_id'        => $user_id,
            'jenis_pesan'    => $jenis_pesan,
            'no_meja'        => $no_meja
        ]);

        $sale_id = $this->saleModel->getInsertID();

        // Simpan detail item
        $item_ids = $this->request->getPost('item_id');
        $qtys     = $this->request->getPost('qty');
        $hargas   = $this->request->getPost('total_harga');

        foreach ($item_ids as $i => $item_id) {
            $qty      = (int) $qtys[$i];
            $harga    = (int) $hargas[$i];
            $subtotalItem = $qty * $harga;

            $this->detailModel->save([
                'sale_id'     => $sale_id,
                'item_id'     => $item_id,
                'qty'         => $qty,
                'harga'       => $harga,
                'subtotal'    => $subtotalItem
            ]);

            // Update stok
            $item = $this->itemModel->find($item_id);
            if ($item) {
                $newStock = $item['stok'] - $qty;
                if ($newStock < 0) {
                    $db->transRollback();
                    return redirect()->back()->with('error', 'Stok tidak cukup untuk item: ' . $item['nama']);
                }
                $this->itemModel->update($item_id, ['stok' => $newStock]);
            }
        }

        $db->transCommit();
        session()->setFlashdata('print_sale_id', $sale_id);
        return redirect()->to(base_url('admin/sales/create'));

    } catch (\Throwable $e) {
        $db->transRollback();
        return redirect()->back()->withInput()->with('error', 'Gagal menyimpan transaksi: ' . $e->getMessage());
    }
}



    public function print($id)
    {
        $sale = $this->saleModel->getJoinById($id);
        $details = $this->detailModel->getDetailBySale($id);

        if (!$sale) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("Transaksi tidak ditemukan");
        }

        $settingModel = new SettingModel();
        $receiptSetting = $settingModel->getReceiptSetting();
        $layoutRaw = $settingModel->get('receipt_layout');
        $layout = $layoutRaw ? json_decode($layoutRaw, true) : [];

        return view('sales/print', [
            'title'   => 'Cetak Struk',
            'sale'    => $sale,
            'details' => $details,
            'layout'  => $layout,
            'receipt' => $receiptSetting
        ]);
    }

    public function print_android($id)
{
    $saleModel = new SaleModel();
    $detailModel = new SaleDetailModel();
    $settingModel = new SettingModel();

    $data['sale'] = $saleModel->find($id);
    $data['details'] = $detailModel->where('sale_id', $id)->findAll();
    $data['receipt'] = $settingModel->getReceiptSetting();
    $data['title'] = 'Cetak Android';

    // Debug sementara untuk melihat isi data
    // dd($data['sale']);

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


    public function detail($id)
    {
        $sale = $this->saleModel->getJoinById($id);
        $items = $this->saleDetailModel->getBySaleId($id);

        if (!$sale) {
            return 'Data tidak ditemukan.';
        }

        return view('sales/detail', [
            'sale'  => $sale,
            'items' => $items
        ]);
    }
}
