<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use App\Models\HeaderCoa;
use App\Models\MasterCoa;
use App\Models\Pembelian;
use Yajra\DataTables\Facades\DataTables;
use App\Exports\PembelianExport;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;

class PembelianController extends Controller
{
    public function index()
    {

        return view('pembelian.index');
    }

    public function exportExcel(Request $request)
    {
        [$year, $month] = explode('-', $request->input('month'));
        setlocale(LC_TIME, 'id_ID.UTF-8');
        Carbon::setLocale('id');
        $bulanIndonesia = Carbon::createFromFormat('m', $month)->translatedFormat('F');

        return Excel::download(new PembelianExport($month, $year, $bulanIndonesia), 'pembelian ' . $bulanIndonesia . ' ' . $year . '.xlsx');
    }

    public function exportPDF(Request $request)
    {
        [$year, $month] = explode('-', $request->input('month'));
        setlocale(LC_TIME, 'id_ID.UTF-8');
        Carbon::setLocale('id');
        $bulanIndonesia = Carbon::createFromFormat('m', $month)->translatedFormat('F');
        $data = Pembelian::whereYear('tanggal', $year)
            ->whereMonth('tanggal', $month)
            ->get();

        $pdf = PDF::loadView('pembelian.pdf', compact('data', 'month', 'year', 'bulanIndonesia'))->setPaper('A4', 'landscape');
        return $pdf->download('pembelian ' . $bulanIndonesia . ' ' . $year . '.pdf');
    }

    public function create()
    {
        //$data = HeaderCoa::all();
        return view('pembelian.create');
    }
    public function edit($id)
    {
        //$foto = Slider::all();
        //dd($sejarah);
        $data = Pembelian::findOrFail($id);


        //dd($detail);
        return view('pembelian.edit', compact('data'));
    }

    public function store(Request $request)
    {
        $storeData = [
            'tanggal' => $request->input('tanggal'),
            'no_faktur' => $request->input('no_faktur'),
            'keterangan' => $request->input('keterangan'),
            'ref' => $request->input('ref'),
            'biaya_angkut' => str_replace('.', '', $request->input('biaya_angkut')),
            'ppn_masukan' => str_replace('.', '', $request->input('ppn_masukan')),
            'ppn' => $request->input('ppn'),
            'persediaan_barang' => str_replace('.', '', $request->input('persediaan_barang')),
            'hutang_dagang' => str_replace('.', '', $request->input('hutang_dagang')),
            'discount' => $request->input('discount'),
            'nominal_diskon' => str_replace('.', '', $request->input('nominal_diskon')),
            'id_user' => Auth::user()->id
        ];
        Pembelian::create($storeData);

        //return redirect()->route('header_coa.edit', $header->id)->with('alert-success', 'Success Tambah Data');\
        return redirect('pembelian')->with('alert-success', 'Success tambah data');
    }

    public function update(Request $request, $id)
    {
        $updateData = [
            'tanggal' => $request->input('tanggal'),
            'no_faktur' => $request->input('no_faktur'),
            'keterangan' => $request->input('keterangan'),
            'ref' => $request->input('ref'),
            'biaya_angkut' => str_replace('.', '', $request->input('biaya_angkut')),
            'ppn_masukan' => str_replace('.', '', $request->input('ppn_masukan')),
            'ppn' => $request->input('ppn'),
            'persediaan_barang' => str_replace('.', '', $request->input('persediaan_barang')),
            'hutang_dagang' => str_replace('.', '', $request->input('hutang_dagang')),
            'discount' => $request->input('discount'),
            'nominal_diskon' => str_replace('.', '', $request->input('nominal_diskon')),
            'id_user' => Auth::user()->id
        ];
        Pembelian::where('id', $id)->update($updateData);


        return redirect('pembelian')->with('alert-success', 'Success update data');
        //return redirect()->route('pembelian.edit', $id)->with('alert-success', 'Success Update Data');
    }

    public function destroy($id)
    {
        Pembelian::findOrFail($id)->delete();
        //MasterCoa::where('id_header_coa', $id)->delete();
        return redirect('pembelian')->with('alert-success', 'Success deleted data');
    }

    public function getData(Request $request)
    {
        if ($request->ajax()) {
            $query = Pembelian::select('pembelian.*');

            // Filter berdasarkan month (format: YYYY-MM)
            if ($request->filled('month')) {
                [$year, $month] = explode('-', $request->input('month'));
                $query->whereYear('tanggal', $year)
                    ->whereMonth('tanggal', $month);
            }

            $data = $query->orderBy('pembelian.id', 'desc')
                ->get()
                ->map(function ($item) {
                    $item->tanggal = $item->tanggal
                        ? \Carbon\Carbon::parse($item->tanggal)->format('d/m/Y')
                        : null;
                    $item->biaya_angkut = number_format($item->biaya_angkut);
                    $item->ppn_masukan = number_format($item->ppn_masukan);
                    $item->persediaan_barang = number_format($item->persediaan_barang);
                    $item->hutang_dagang = number_format($item->hutang_dagang);

                    return $item;
                });

            return Datatables::of($data)
                ->addColumn('action', function ($row) {
                    $editRoute = route('pembelian.edit', ['pembelian' => $row->id]);
                    $deleteRoute = route('pembelian.destroy', ['pembelian' => $row->id]);
                    $btn = '<form method="POST" action="' . $deleteRoute . '" style="margin-left: 10px;" onsubmit="return confirm(\'Apakah anda yakin?\')">';
                    $btn .= '<div class="btn-group">';
                    $btn .= '<a href="' . $editRoute . '" class="btn btn-warning">Edit</a>';
                    $btn .= '<button type="submit" class="btn btn-danger ml-2">Hapus</button>';
                    $btn .= csrf_field();
                    $btn .= method_field("DELETE");
                    $btn .= '</div>';
                    $btn .= '</form>';

                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }
}
