<?php

namespace App\Http\Controllers;

use App\Models\HeaderCoa;

use App\Models\MasterCoa;

//use App\Models\HeaderCoa;
use App\Models\Pembelian;
use App\Models\Penerimaan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\Facades\DataTables;
use App\Exports\PenerimaanExport;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;

class PenerimaanController extends Controller
{
    public function index()
    {

        return view('penerimaan.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 PenerimaanExport($month, $year, $bulanIndonesia), 'penerimaan ' . $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 = Penerimaan::select(
            'penerimaan.*',
            'coa_debet.nama_akun as nama_akun_debet',
            'coa_kredit.nama_akun as nama_akun_kredit'
        )
            ->leftJoin('master_coa as coa_debet', 'coa_debet.no_akun', '=', 'penerimaan.no_akun_debet')
            ->leftJoin('master_coa as coa_kredit', 'coa_kredit.no_akun', '=', 'penerimaan.no_akun_kredit')
            ->whereYear('penerimaan.tanggal', $year)
            ->whereMonth('penerimaan.tanggal', $month)
            ->get();

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

    public function create()
    {
        // $master_coa = MasterCoa::orderBy('no_akun', 'asc')
        //     ->orderBy('nama_akun', 'asc')
        //     ->get();
        $header_coa = HeaderCoa::with(['masterCoa' => function ($query) {
            $query->orderBy('no_akun')->orderBy('nama_akun');
        }])
            ->orderBy('no_header_akun')
            ->orderBy('nama_header_akun')
            ->get();

        return view('penerimaan.create', compact('header_coa'));
    }
    public function edit($id)
    {
        //$foto = Slider::all();
        //dd($sejarah);
        $data = Penerimaan::findOrFail($id);
        // $master_coa = MasterCoa::orderBy('no_akun', 'asc')
        //     ->orderBy('nama_akun', 'asc')
        //     ->get();

        $header_coa = HeaderCoa::with(['masterCoa' => function ($query) {
            $query->orderBy('no_akun')->orderBy('nama_akun');
        }])
            ->orderBy('no_header_akun')
            ->orderBy('nama_header_akun')
            ->get();

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

    public function store(Request $request)
    {
        $storeData = [
            'tanggal' => $request->input('tanggal'),
            'no_akun_debet' => $request->input('no_akun_debet'),
            'no_akun_kredit' => $request->input('no_akun_kredit'),
            'debet' => str_replace('.', '', $request->input('debet')),
            'kredit' => str_replace('.', '', $request->input('kredit')),
            'keterangan' => $request->input('keterangan'),
            'id_user' => Auth::user()->id
        ];
        Penerimaan::create($storeData);

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

    public function update(Request $request, $id)
    {
        $updateData = [
            'tanggal' => $request->input('tanggal'),
            'no_akun_debet' => $request->input('no_akun_debet'),
            'no_akun_kredit' => $request->input('no_akun_kredit'),
            'debet' => str_replace('.', '', $request->input('debet')),
            'kredit' => str_replace('.', '', $request->input('kredit')),
            'keterangan' => $request->input('keterangan'),
            'id_user' => Auth::user()->id
        ];
        Penerimaan::where('id', $id)->update($updateData);


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

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

    public function getData(Request $request)
    {
        if ($request->ajax()) {
            $query = Penerimaan::select(
                'penerimaan.*',
                'coa_debet.nama_akun as nama_akun_debet',
                'coa_kredit.nama_akun as nama_akun_kredit'
            );
            if ($request->filled('month')) {
                [$year, $month] = explode('-', $request->input('month'));
                $query->whereYear('penerimaan.tanggal', $year)
                    ->whereMonth('penerimaan.tanggal', $month);
            }
            $data = $query->leftJoin('master_coa as coa_debet', 'coa_debet.no_akun', '=', 'penerimaan.no_akun_debet')
                ->leftJoin('master_coa as coa_kredit', 'coa_kredit.no_akun', '=', 'penerimaan.no_akun_kredit')
                ->orderBy('penerimaan.id', 'desc')
                ->get()
                ->map(function ($item) {
                    $item->tanggal = $item->tanggal
                        ? \Carbon\Carbon::parse($item->tanggal)->format('d/m/Y')
                        : null;
                    $item->debet = number_format($item->debet);
                    $item->kredit = number_format($item->kredit);


                    return $item;
                });


            //ddd($data);
            return Datatables::of($data)
                ->addColumn('action', function ($row) {
                    $editRoute = route('penerimaan.edit', ['penerimaan' => $row->id]);
                    //$showRoute = route('header_coa.show', ['header_coa' => $row->id]);
                    $deleteRoute = route('penerimaan.destroy', ['penerimaan' => $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 .= '<a href="' . $showRoute . '" class="btn btn-success ml-2">Detail</a>';
                    $btn .= '<button type="submit" class="btn btn-danger ml-2">Hapus</button>';
                    $btn .= csrf_field(); // Blade directive for CSRF token
                    $btn .= method_field("DELETE"); // Blade directive for HTTP method spoofing

                    $btn .= '</div>';
                    $btn .= '</form>';

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

    public function cekDuplikat(Request $request)
    {
        $exists = Penerimaan::where('tanggal', $request->tanggal)
            ->where('no_akun_debet', $request->id_coa_debet)
            ->where('no_akun_kredit', $request->id_coa_kredit)
            ->where('debet', $request->debet)
            ->where('kredit', $request->kredit)
            ->when($request->id, function ($query) use ($request) {
                // Hindari membandingkan dirinya sendiri
                $query->where('id', '!=', $request->id);
            })
            ->exists();

        return response()->json([
            'duplikat' => $exists
        ]);
    }
}
