<?php



namespace App\Http\Controllers\Api;



use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Auth;

use App\Models\Journal;

use App\Models\JournalEntry;

use App\Service\JournalEntryService;

use App\Service\UploadService;

use App\Service\CurrencyConvertService;

use App\Service\ActivityService;
use App\Service\SequenceService;

use App\Service\TransactionService;

use Carbon\Carbon;
use App\Service\StaticMaster;


class JournalEntryController extends Controller

{

    public function journalCreateUpdate(Request $request){

        // Validate 

        $validator=validator($request->all(),[

            'journal_no'=>'required',

            'fy'=>'required',

            'transaction_date'=>'required',

            'journal_entries'=>'required',

            'sub_total_credit'=>'required',

            'sub_total_debit'=>'required'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            $data=[

                'fy',

                'transaction_date',

                'journal_no',

                'reference',

                'notes',

                'journal_type', // 0:not cash based journal , 1:cash based journal

                'currency',

                'sub_total_credit',

                'sub_total_debit',

                'total_debit',

                'total_credit',

                'difference',

                'custome_note',

                'upload_image',

                'status',

                'customer_id'

            ];

            foreach ($data as $key => $value) {

                if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){

                    $obj[$value]=$request[$value];

                }

                // if($request[$value]==''){

                //     $obj[$value]=null;

                // }

                // if($request[$value]==0){

                //     $obj[$value]=0;

                // }

            }

            // Services to create Record

            $uploadService=new UploadService;

            $journalEntries=new JournalEntryService;

            $currency_convert=new CurrencyConvertService;

            $obj['transaction_type']=StaticMaster::$JOURNAL;

            if($request['id']>0){

                try{

                    //Check if id is already exists

                    $journal=Journal::findOrFail($request['id']);

                    $journal->update($obj);

                    // Creating Activities

                    $activity=new ActivityService;

                    $activity->activityCreateUpdate('Journal',$journal['id'],'Updated');

                    // Delete Existing Items

                    $journal_entry=JournalEntry::where('journal_id',$request['id'])->delete();

                    // Creating Entries

                    $journalEntries->journalEntries($request,$journal);

                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                    // Return error message in JSON if ID not found

                    return response()->json(['message' => 'Invalid Id to update '], 404);

                }

            }else{

                $journal=Journal::create($obj);

                $module='journal';
                // Update Sequence Number
                $sequence=new SequenceService;
                $sequence->updateSequence($module);

                // Creating Activities
                $activity=new ActivityService;
                $activity->activityCreateUpdate('Journal',$journal['id'],'Created');

                $journal['documents']= $uploadService->uploadfile($request);

                // $journal['exchange_rate']=$currency_convert->getlatestCurrency($request['currency']);
                // $journal['exchange_rate']=$request['currency'];

                $journal->update();

                // Creating Entries
                $journalEntries->journalEntries($request,$journal);

            }     

            $response=[

                'message'=> $request['id']>0? "Journal Updated Successfully":"Journal Created Successfully",
            
                'success'=>true,

            ];



            return response()->json($response);

        }

    }



    public function journalList(Request $request){

        $user=Auth::user();

         // Validate Item

         $validator=validator($request->all(),[

            'fy'=>'required'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            $journal= Journal::where('organisation_id',$user['active_organisation'])

                ->with("journal_entry")

                ->where('fy',$request['fy']);

            if(isset($request['status'])){

                $journal=$journal->where('status',$request['status']);

            }

            if($request['search']!=null && $request['search']!=''){

                $journal = $journal->where('journal_no', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('reference', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('total_debit', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('notes', 'LIKE', '%' . $request['search'] . '%');

            }

            if(isset($request['today']) && $request['today']) {

                $journal = $journal->whereDate('transaction_date', $request['today']);

            }

        
            if(isset($request['this_week']) && $request['this_week']) {

                // Get the start and end of the week

                $startOfWeek = Carbon::now()->startOfWeek()->toDateString();

                $endOfWeek = Carbon::now()->endOfWeek()->toDateString();

                $journal = $journal->whereBetween('transaction_date', [$startOfWeek, $endOfWeek]);

            }

            if(isset($request['this_month']) && $request['this_month']) {

            
                // Get the start and end of the month

                $startOfMonth = Carbon::now()->startOfMonth()->toDateString();

                $endOfMonth = Carbon::now()->endOfMonth()->toDateString();

                $journal = $journal->whereBetween('transaction_date', [$startOfMonth, $endOfMonth]);

            }            

            if(isset($request['this_quarter']) && $request['this_quarter']) {
                // Get the start and end dates of the quarter

                $startOfQuarter = Carbon::now()->startOfQuarter()->toDateString();

                $endOfQuarter = Carbon::now()->endOfQuarter()->toDateString();

        
                $journal = $journal->whereBetween('transaction_date', [$startOfQuarter, $endOfQuarter]);

            }

            if(isset($request['this_year']) && $request['this_year']) {
                // Get the start and end dates of the year

                $startOfYear = Carbon::now()->startOfYear()->toDateString();

                $endOfYear = Carbon::now()->endOfYear()->toDateString();

                $journal = $journal->whereBetween('transaction_date', [$startOfYear, $endOfYear]);

            }

            $count=$journal->count();


            $journal=$journal->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)

                ->orderBy('id','desc')

                    ->get();

            $response=[

                'message'=>'Journal List Fetched Successfully',

                'journal'=>$journal,

                'count'=>$count,

                'success'=>true

            ];
            return response()->json($response);

        }

    }



    public function journalDetails(Request $request){

        $user=Auth::user();

         // Validate Item

         $validator=validator($request->all(),[

            'journal_id'=>'required'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            $journal=Journal::where('id',$request['journal_id'])

                ->where('organisation_id',$user['active_organisation'])

                ->with('journal_entry','activity','journal_entry.account:id,account_name,account_code','journal_entry.customer')

                ->first();
                
            $response=[

                'message'=>'Journal Details fetched Successfully',

                'data'=>$journal,

                'success'=>true

            ];



            return response()->json($response);

        }

    }



    public function journalApproved(Request $request){

        $user=Auth::user();

         // Validate Item
         $validator=validator($request->all(),[
            'journal_id'=>'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            $journal=Journal::where('id',$request['journal_id'])
                ->where('organisation_id',$user['active_organisation'])
                ->where('is_approved',0)
                ->with('journal_entry')
                ->first();

            if($journal!=null){

                $journal_entry=JournalEntry::where('journal_id',$journal['id'])->get();

                // Transaction service
                $transaction=new TransactionService; 

                foreach ($journal_entry as $key => $value) {

                    // Creating entry for transactions below
                    $transaction->createJournalTransaction($journal,$value);
                }

                $journal['is_approved']=1;
                $journal['status']=1;

                $journal->update();

                // Creating Activities
                $activity=new ActivityService;
                $activity->activityCreateUpdate('Journal Approved',$journal['id'],'Approved');

                $response=[
                    'message'=>'Journal Approved Successfully',
                    'data'=>$journal,
                    'success'=>true
                ];

            }else{

                $response=[
                    'message'=>'Journal Not found or It is Already Approved',
                    'data'=>null,
                    'success'=>false
                ];
            }

            return response()->json($response);
        }   

        
    }



    public function currency(Request $request){

        //return Currency::getCurrenciesByCountry($request['country']);



        $currency_convert=new CurrencyConvertService;

        // $currency_object=$currency_convert->getlatestCurrency($request['currency']);



        $sanitized_currency = filter_var($request['currency'], FILTER_SANITIZE_STRING);



        if(is_string($currency_object)){

            return response()->json(["value"=>$currency_object,'string'=>1]);

        }else{

            return response()->json(["value"=>$currency_object,'string'=>0]);

        }



        

    }

}

