<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Http\Controllers\RandomNumbersController;
use App\Models\AccBillsManager;
use App\Models\AccVendor;
use App\Models\BillMasterVendor;
use App\Models\DocsBill;
use App\Models\Requisition;
use Illuminate\Http\Request;

class AccBillsManagerController extends Controller
{
    public function index(){
        $lists =  AccVendor::orderBy('name', 'asc')->get();

        return view('finance.bills.acc-bills-manager', compact('lists'));
    }

    /**Display Pop Up window to store a New Bill**/
    public function showNewBill(){
        $vendors = AccVendor::where('status', 1)->orderBy('name', 'ASC')->get();
        return view('finance.bills.add-new-bill', compact('vendors'));
    }

    /**A Function to Store a Bill**/
    public function storeNewBill(Request $request){
        $branch = $request['branch'];
        $vendor = $request['vendor'];
        $ledger = $request['ledger'];
        $amount = $request['bill-gross-amount'];
        $ref = $request['ref'];
        $date = $request['bill-date'];
        $due_date = $request['bill-due-date'];
        $narration = $request['narration'];

        $res = 'empty fields';
        if(!empty($vendor) && !empty($ledger) && !empty($amount) && !empty($ref) && !empty($due_date) && !empty($narration)){
            $res = 'zero amount';
            if($amount > 0){
                /**Check if the Bill already Exists**/
                $billExists = AccBillsManager::where('vendor_id', $vendor)->where('ledger_id', $ledger)->where('ref', $ref)->where('amount', $amount)->first();
                $res = 'bill exists';
                if(!$billExists){
                    /**At this stage, prepare to Store the Bill**/
                    $stamp = (new RandomNumbersController)->getRandomMix(10);
                    $res = 'stamp exist';
                    if(!AccBillsManager::where('stamp', $stamp)->first()){
                        $createBill =AccBillsManager::create(
                            [
                                'branch' => $branch,
                                'vendor_id' => $vendor,
                                'ledger_id' => $ledger,
                                'amount' => $amount,
                                'ref' => $ref,
                                'narration' => $narration,
                                'stamp' => $stamp,
                                'date' =>  $date ?? date('Y-m-d'),
                                'due_date' =>  $due_date,
                                'created_by' => auth()->user()->id,
                            ]
                        );

                        $res = 'error';
                        if($createBill){
                            /**Since a Bill has Successfully been Created, Add the Entry in Bill Master for Vendors:- This will assist to compile Vendor Statements**/
                            $createBillMaster = BillMasterVendor::create(
                                [
                                    'vendor_id' =>  $vendor,
                                    'bill_id' =>  $createBill->id,
                                    'type' =>  'credit',
                                    'ref' =>  $ref,
                                    'date' =>  $date ?? date('Y-m-d'),
                                    'due_date' =>  $due_date,
                                    'trans_type' =>  'BILL',
                                    'details' =>  $narration,
                                    'amount' =>  $amount,
                                ]
                            );
                            $res = 'error bill master';
                            if($createBillMaster){
                                $res = 'success';
                            }
                        }
                    }
                }
            }
        }
        return $res;
    }

    /**A Bill has a certain Amount of Money paid to It**/
    public function billPaidAmount($id){
        /**Above Id is the bill_id**/
        $paidAmount = 0;
        if(BillMasterVendor::where('bill_id',$id)->where('trans_type', 'PAYMENT')->first()){
            $paidAmount = BillMasterVendor::where('bill_id',$id)->where('trans_type', 'PAYMENT')->sum('amount');
        }
        return $paidAmount;
    }

    /**Create a Function to get a Bill's Current Balance**/
    public function billBalance($id){
        $billBalance = 0;
        $bill = AccBillsManager::find($id);
        if($bill){
            $billBalance = $bill->amount + $this->billPaidAmount($id);
        }
        return $billBalance;
    }

    /**Display a Page where by the User Can View or Upload Bill Documents**/
    public function showUploadBillDocuments($id){
        $bill = AccBillsManager::findOrFail($id);

        return view('finance.bills.view-or-upload-bill-documents', compact('id', 'bill'));
    }

    /**Upload the Bill Documents into the System**/
    public function storeUploadBillDocuments($id, Request $request){
        $res = "no file attached";
        /**Upload File 1**/
        if($request->hasFile('upload-doc-one')){
            $res = 'empty name one';
            if(!empty($request['file-name-one'])){
                $filepathOne = $request->file('upload-doc-one');
                $nameOne = $request['file-name-one'];
                $fileExtension = $filepathOne->getClientOriginalExtension();
                $filenameOne = $nameOne."_".time().".".$fileExtension;

                /**By Default - We define the Destination Path **/
                $destinationPath = 'uploads/docs/vendors/bills';
                //store the file now
                $pathOne = $request['upload-doc-one']->move(public_path($destinationPath), $filenameOne);
                $res = 'error uploading';
                if($pathOne){
                    /**Store the Info into the Documents table **/
                    $res = 'error';
                    if(DocsBill::create([
                        'bill_id' => $id,
                        'filename' => $nameOne,
                        'path' => $destinationPath."/".$filenameOne,
                        'status' => 1,
                        'created_by' => auth()->user()->id,
                    ])){
                        $res = 'success';
                    }
                }
            }
        }
        /**Upload File 2**/
        if($request->hasFile('upload-doc-two')){
            $res = 'empty name two';
            if(!empty($request['file-name-two'])){
                $filepathTwo = $request->file('upload-doc-two');
                $nameTwo = $request['file-name-two'];
                $fileExtension = $filepathTwo->getClientOriginalExtension();
                $filenameTwo = $nameTwo."_".time().".".$fileExtension;

                /**By Default - We define the Destination Path **/
                $destinationPath = 'uploads/docs/vendors/bills';
                //store the file now
                $pathTwo = $request['upload-doc-two']->move(public_path($destinationPath), $filenameTwo);
                $res = 'error uploading';
                if($pathTwo){
                    /**Store the Info into the Documents table **/
                    $res = 'error';
                    if(DocsBill::create([
                        'bill_id' => $id,
                        'filename' => $nameTwo,
                        'path' => $destinationPath."/".$filenameTwo,
                        'status' => 1,
                        'created_by' => auth()->user()->id,
                    ])){
                        $res = 'success';
                    }
                }
            }
        }
        return $res;
    }

    /**Display Payments Made to a specific Bill**/
    public function showBillPaymentDetails($id)
    {
        $bill = AccBillsManager::find($id);
        /**Get all Paid Requisitions to this Bill**/
        $paidReqs = Requisition::where('req_type', 'bill-payment')->where('batch', $id)->where('req_status', 'paid')->get();

        return view('finance.bills.view-bill-payment-details', compact('bill','paidReqs'));
    }

}
