<?php

namespace App\Http\Controllers;

use App\Models\Cashtransaction;
use App\Models\Subcashtransaction;
use App\Models\VatEntry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VatEntryController extends Controller
{
    public function index()
    {
        $entries = VatEntry::orderBy('date', 'desc')->orderBy('id', 'desc')->get();

        return response([
            'success' => true,
            'data' => $entries
        ], 200);
    }

    public function show($id)
    {
        $entry = VatEntry::find($id);

        if (!$entry) {
            return response([
                'success' => false,
                'message' => 'VAT entry not found'
            ], 404);
        }

        return response([
            'success' => true,
            'data' => $entry
        ], 200);
    }

    public function getByDate($date)
    {
        $entries = VatEntry::whereDate('date', $date)
            ->orderBy('id', 'desc')
            ->get();

        return response([
            'success' => true,
            'data' => $entries
        ], 200);
    }

    public function getUnpaidUnderpaid()
    {
        $entries = VatEntry::whereNotNull('total_underpaid')
            ->where(function ($query) {
                $query->whereNull('paid')
                    ->orWhere('paid', 0);
            })
            ->orderBy('date', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        return response([
            'success' => true,
            'data' => $entries
        ], 200);
    }

    public function setPaid(Request $request, $id)
    {
        $validated = $request->validate([
            'paid' => 'required|numeric|min:0',
            'cashout_id' => 'required|integer|exists:akuns,id',
            'akun_id' => 'required|integer|exists:akuns,id',
            'transaction_category' => 'required|string',
            'date' => 'required|date',
            'staff' => 'required|string',
            'desc' => 'nullable|string',
        ]);

        $entry = VatEntry::find($id);
        if (!$entry) {
            return response([
                'success' => false,
                'message' => 'VAT entry not found'
            ], 404);
        }

        DB::beginTransaction();
        try {
            $entry->paid = $validated['paid'];
            $entry->save();

            $cash = new Cashtransaction;
            $cash->from = $validated['cashout_id'];
            $cash->staff = $validated['staff'];
            $cash->date = date("Y-m-d", strtotime($validated['date']));
            $cash->transaction_category = $validated['transaction_category'];
            $cash->vat_entry_id = $entry->id;
            $cash->cashout = $validated['paid'];
            $cash->cashin = 0;
            $cash->transfer = 0;
            $cash->save();

            $sub = new Subcashtransaction;
            $sub->cashtransaction_id = $cash->id;
            $sub->akun_id = $validated['akun_id'];
            $sub->total = $validated['paid'];
            $sub->desc = $validated['desc'] ?? null;
            $sub->save();

            DB::commit();

            return response([
                'success' => true,
                'message' => 'VAT entry paid successfully',
                'data' => [
                    'vat_entry' => $entry,
                    'cashtransaction' => $cash
                ]
            ], 200);
        } catch (\Exception $e) {
            DB::rollback();

            return response([
                'success' => false,
                'message' => 'Failed to set paid: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'input_vat' => 'nullable|numeric',
            'output_vat' => 'nullable|numeric',
            'overpaid_vat' => 'nullable|numeric',
            'transaction_category' => 'required|string',
            'date' => 'required|date',
            'staff' => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $entry = new VatEntry;
            $entry->input_vat = $validated['input_vat'] ?? null;
            $entry->output_vat = $validated['output_vat'] ?? null;
            $entry->overpaid_vat = $validated['overpaid_vat'] ?? null;

            $inputVat = (float) ($validated['input_vat'] ?? 0);
            $outputVat = (float) ($validated['output_vat'] ?? 0);
            $overpaidVat = (float) ($validated['overpaid_vat'] ?? 0);
            $baseVat = $inputVat + $overpaidVat;

            if ($outputVat > $baseVat) {
                $entry->total_overpaid = 0;
                $entry->total_underpaid = $outputVat - $baseVat;
            } elseif ($outputVat < $baseVat) {
                $entry->total_overpaid = $baseVat - $outputVat;
                $entry->total_underpaid = 0;
            } else {
                $entry->total_overpaid = 0;
                $entry->total_underpaid = 0;
            }

            $entry->transaction_category = $validated['transaction_category'] ?? null;
            $entry->date = date("Y-m-d", strtotime($request->date));
            $entry->staff = $validated['staff'] ?? null;
            $entry->save();

            DB::commit();

            return response([
                'success' => true,
                'message' => 'VAT entry created successfully',
                'data' => $entry
            ], 201);
        } catch (\Exception $e) {
            DB::rollback();
            return response([
                'success' => false,
                'message' => 'Failed to create VAT entry: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $entry = VatEntry::find($id);

        if (!$entry) {
            return response([
                'success' => false,
                'message' => 'VAT entry not found'
            ], 404);
        }

        $validated = $request->validate([
            'input_vat' => 'nullable|numeric',
            'output_vat' => 'nullable|numeric',
            'overpaid_vat' => 'nullable|numeric',
            'transaction_category' => 'required|string',
            'date' => 'required|date',
            'staff' => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $entry->input_vat = $validated['input_vat'] ?? null;
            $entry->output_vat = $validated['output_vat'] ?? null;
            $entry->overpaid_vat = $validated['overpaid_vat'] ?? null;

            $inputVat = (float) ($validated['input_vat'] ?? 0);
            $outputVat = (float) ($validated['output_vat'] ?? 0);
            $overpaidVat = (float) ($validated['overpaid_vat'] ?? 0);
            $baseVat = $inputVat + $overpaidVat;

            if ($outputVat > $baseVat) {
                $entry->total_overpaid = 0;
                $entry->total_underpaid = $outputVat - $baseVat;
            } elseif ($outputVat < $baseVat) {
                $entry->total_overpaid = $baseVat - $outputVat;
                $entry->total_underpaid = 0;
            } else {
                $entry->total_overpaid = 0;
                $entry->total_underpaid = 0;
            }

            $entry->transaction_category = $validated['transaction_category'] ?? null;
            $entry->date = date("Y-m-d", strtotime($request->date));
            $entry->staff = $validated['staff'] ?? null;
            $entry->save();

            DB::commit();

            return response([
                'success' => true,
                'message' => 'VAT entry updated successfully',
                'data' => $entry
            ], 200);
        } catch (\Exception $e) {
            DB::rollback();
            return response([
                'success' => false,
                'message' => 'Failed to update VAT entry: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function destroy($id)
    {
        $entry = VatEntry::find($id);

        if (!$entry) {
            return response([
                'success' => false,
                'message' => 'VAT entry not found'
            ], 404);
        }

        if ($entry->paid > 0) {
            $cashIds = $entry->cashtransactions()->pluck('id')->implode(', ');
            return response([
                'success' => false,
                'message' => "Transaksi ini telah dibayar BAYAR PPN no.{$cashIds}, untuk hapus ini silakan hapus transaksi di BAYAR PPN dulu"
            ], 400);
        }

        $entry->delete();

        return response([
            'success' => true,
            'message' => 'VAT entry deleted successfully'
        ], 200);
    }
}
