<?php

namespace App\Http\Controllers;

use App\Employees;
use App\PaymetVoucher;
use App\Http\Controllers\Controller;
use App\Payment;
use App\TransactionAccount;
use App\Voucher;
use App\VouchersUniqueNumber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;

class PaymetVoucherController extends Controller
{

    public function index()
    {
        // $vouchersNumber = VouchersUniqueNumber::with('vouchers')->where('voucher_type', 'Payment Voucher')->get();

        return view('paymet_voucher.index');
    }
    public function voucher_listing(Request $request)
    {
        // Fetch vouchers with related vouchers and necessary fields
        $vouchers = VouchersUniqueNumber::with(['vouchers' => function ($query) {
            $query->select(
                'vouchers.*',
                'account_title',
                'business_partner_type',
                'partner_name',
                DB::raw('IFNULL(debit, 0) as debit'),
                DB::raw('IFNULL(credit, 0) as credit')
            );
        }])->where('voucher_type', 'Payment Voucher')->get();

        // Return a DataTable instance, but treat each voucher as a new row

        return DataTables::of($vouchers->flatMap(function ($vouchersUnique) {

            return $vouchersUnique->vouchers->map(function ($voucher) use ($vouchersUnique) {

                return [
                    'voucher_number' => $vouchersUnique->voucher_number,
                    'voucher_date' => date('d F Y', strtotime($voucher->date)),
                    'debit' => number_format($voucher->debit, 2),
                    'credit' => number_format($voucher->credit, 2),
                    'account_title' => $voucher->account_title ?? '', // Transaction account name
                    'bp_type' => $voucher->business_partner_type ?? '', // Business partner type
                    'bp_name' => $voucher->partner_name ?? '',
                    'action' => '<a class="btn btn-outline-success btn-sm rounded-pill shadow-sm" '
                        . 'title="View Payment Voucher" '
                        . 'href="' . route('voucher.p_view', Crypt::encrypt($voucher->vouchers_unique_number_id)) . '" '
                        . 'target="_blank"><i class="fa-solid fa-eye"></i> View</a>'
                ];
            });
        }))
            ->rawColumns(['action']) // Ensure action column is processed as raw HTML
            ->make(true);
    }

    public function create()
    {

        $employees = Employees::all();
        $accounts = TransactionAccount::all();
        return view('paymet_voucher.create', compact('employees', 'accounts'));
    }

    public function store(Request $request)
    {
        // Validate the incoming data
        $request->validate([
            'voucherDate.*' => 'required|date',
            'accountNo.*' => 'required|string',
            'accountName.*' => 'required|string',
            'paymentMode.*' => 'required|string',
            'instrumentAmount.*' => 'nullable|string',
            'netAmount.*' => 'required|numeric',
            'noteRemarks.*' => 'nullable|string',
            'debitAMount.*' => 'nullable|numeric',
            'creditAmount.*' => 'nullable|numeric',
            'businessPartnerName.*' => 'nullable|string',
            'taxDebitYesNo.*' => 'required|string',
            'transactionAccountId.*' => 'required|string',
            'transactionAccountName.*' => 'required|string',
            'vDescription.*' => 'nullable|string',
            // 'voucherStatus.*' => 'required|string',
        ]);

        // Generate a unique journal voucher number (e.g., JV-XXXXX)
        $uniqueVoucherNumber = 'PV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

        // Create a new VouchersUniqueNumber record
        $voucherUniqueNumber = new VouchersUniqueNumber();
        $voucherUniqueNumber->voucher_type = 'Payment Voucher';
        $voucherUniqueNumber->voucher_number = $uniqueVoucherNumber;
        $voucherUniqueNumber->save();  // Save the unique voucher number record first

        // Loop through each row and create a voucher record
        for ($i = 0; $i < count($request->accountNo); $i++) {
            $voucher = new Voucher();
            $voucher->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;  // Associate with unique voucher number
            $voucher->date = $request->voucherDate[$i];
            $voucher->account_no = $request->accountNo[$i];
            $voucher->account_title = $request->accountName[$i];
            $voucher->payment_mode = $request->paymentMode[$i];
            $voucher->instrument = $request->instrumentAmount[$i];
            $voucher->business_partner_type = $request->business_partner;
            $voucher->partner_name = $request->partner_name;
            $voucher->transaction_acc_no = $request->transaction_account;
            $voucher->transaction_acc_name = $request->transaction_account;
            $voucher->amount = $request->netAmount[$i];
            $voucher->remarks = $request->noteRemarks[$i];
            $voucher->debit = $request->debitAmount[$i];
            $voucher->credit = $request->creditAmount[$i];
            $voucher->tax_debit = $request->taxDebitYesNo[$i];
            $voucher->desciption = $request->vDescription[$i];
            $voucher->status = 'Posted';
            // Save the voucher
            $voucher->save();
        }

        // Redirect back with a success message
        return redirect()->route('payment.list')->with('success', 'Vouchers have been created successfully.');
    }


    public function view($id)
    {
        $id = Crypt::decrypt($id);
        $voucherDetails = VouchersUniqueNumber::with('vouchers')->where('voucher_type', 'Payment Voucher')->where('id_vouchers_unique_number', $id)->first();
        $accountVouchers = $voucherDetails->vouchers->where('vouchers_unique_number_id', $id);
        $vou_other_detail = $voucherDetails->vouchers->where('vouchers_unique_number_id', $id)->first();

        return view('paymet_voucher.view', compact('voucherDetails', 'accountVouchers', 'vou_other_detail'));
    }


    public function edit($encryptedId)
    {
        $id = Crypt::decrypt($encryptedId);
        $vouchersNumber = VouchersUniqueNumber::with('vouchers')->where('voucher_type', 'Payment Voucher')->findOrFail($id);

        $voucherSingle = $vouchersNumber->vouchers->first();

        // Fetch employees and accounts for the form
        $employees = Employees::all();
        $accounts = TransactionAccount::all();

        return view('paymet_voucher.edit', compact('employees', 'accounts', 'vouchersNumber', 'voucherSingle'));
    }


    public function update(Request $request, $encryptedId)
    {
        // Validate the request data
        $request->validate([
            'voucherDate.*' => 'required|date',
            'accountNo.*' => 'required|string',
            'accountName.*' => 'required|string',
            'paymentMode.*' => 'required|string',
            'instrumentAmount.*' => 'nullable|string',
            'netAmount.*' => 'required|numeric',
            'noteRemarks.*' => 'nullable|string',
            'debitAMount.*' => 'nullable|numeric',
            'creditAmount.*' => 'nullable|numeric',
            'businessPartnerName.*' => 'nullable|string',
            'taxDebitYesNo.*' => 'required|string',
            'transactionAccountId.*' => 'required|string',
            'transactionAccountName.*' => 'required|string',
            'vDescription.*' => 'nullable|string',
            'voucherStatus.*' => 'required|string',
            'voucherIds.*' => 'nullable|integer'
        ]);


        if ($request->has('deletedVouchers')) {
            $deletedVouchers = explode(',', $request->input('deletedVouchers'));
            Voucher::whereIn('id_vouchers', $deletedVouchers)->delete();
        }

        $id = Crypt::decrypt($encryptedId);
        $voucherUniqueNumber = VouchersUniqueNumber::with('vouchers')->findOrFail($id);
        $existingVouchers = Voucher::where('vouchers_unique_number_id', $voucherUniqueNumber->id_vouchers_unique_number)->get();

        // Track new vouchers to be inserted
        $newVouchersData = [];

        // Track IDs to update and compare against existing ones
        $voucherIdsToUpdate = $request->input('voucherIds', []);
        $existingVoucherIds = $existingVouchers->pluck('id_vouchers')->toArray();

        // Process the vouchers from the request
        foreach ($request->input('voucherDate', []) as $index => $voucherDate) {
            $voucherId = $voucherIdsToUpdate[$index] ?? null;

            // Add new voucher
            $newVouchersData[] = [
                'vouchers_unique_number_id' => $voucherUniqueNumber->id_vouchers_unique_number,
                'date' => $voucherDate,
                'account_no' => $request->input('accountNo.' . $index),
                'account_title' => $request->input('accountName.' . $index),
                'payment_mode' => $request->input('paymentMode.' . $index),
                'instrument' => $request->input('instrumentAmount.' . $index),
                'amount' => $request->input('netAmount.' . $index),
                'remarks' => $request->input('noteRemarks.' . $index),
                'debit' => $request->input('debitAMount.' . $index),
                'credit' => $request->input('creditAmount.' . $index),
                'partner_name' => $request->input('businessPartnerName.' . $index),
                'tax_debit' => $request->input('taxDebitYesNo.' . $index),
                'transaction_acc_no' => $request->input('transactionAccountId.' . $index),
                'transaction_acc_name' => $request->input('transactionAccountName.' . $index),
                'desciption' => $request->input('vDescription.' . $index),
                'status' => $request->input('voucherStatus.' . $index)
            ];
            // dd($voucherId, $existingVoucherIds , $newVouchersData);
        }

        // Insert new vouchers
        if (!empty($newVouchersData)) {
            Voucher::insert($newVouchersData);
        }

        return redirect()->route('payment.list')->with('success', 'Vouchers have been updated, and new vouchers have been added successfully.');
    }




    public function destroy(PaymetVoucher $generalVoucher)
    {
        //
    }
}
