<?php

namespace App\Http\Controllers\API;

use App\Models\Proposal;
use App\Models\Leads\Lead;
use Illuminate\Http\Request;
use App\Models\Contact\Contact;
use App\Models\Product\Product;
use App\Models\ProposalProduct;
use App\Models\Customer\Customer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\API\Proposal\CreateProposalRequest;

/**
 * @method mailToClient($proposal)
 */
class ProposalController extends Controller
{
    /**
     * Get Proposal create page default data
     */
    public function createProposalData(): JsonResponse
    {
        // Get Latest Proposal number and Prefix and make a proposal format
        $biggest_proposal_number = DB::table('proposals')
            ->select(['prefix','proposal_number'])
            ->max('proposal_number');
        $new_proposal_number = sprintf('%06d', $biggest_proposal_number+1);
        $proposal_number_prefix = DB::table('single_row_data')
        ->where(['field_name'=>'proposal_number_prefix'])
        ->first();
        $proposal_default_subject = DB::table('single_row_data')
        ->where(['field_name'=>'proposal_default_subject'])
        ->first();
        if($proposal_number_prefix && $proposal_default_subject){
            return response()->json([
                'message'=>'success',
                'status'=>200,
                'proposal_data'=> [
                    'proposal_number_prefix'=>$proposal_number_prefix->field_value,
                    'proposal_default_subject'=>$proposal_default_subject->field_value,
                    'new_proposal_number'=>$new_proposal_number,
                ]
            ]);
        }else{
            return response()->json([
                'message'=>'no default data',
                'status'=>200,
                'proposal_data'=> [
                    'proposal_number_prefix'=>'PRL-',
                    'proposal_default_subject'=>'Proposal for the products',
                    'new_proposal_number'=>$new_proposal_number,
                ]
            ]);
        }
    }

    /**
     * Validate Proposal Number
     * API-POST
     * return true if available or return available proposal number
     * @param Request $request
     * @return JsonResponse
     */
    public function validateProposalNumber(Request $request): JsonResponse
    {
        $validate_number = DB::table('proposals')->where([
            'proposal_number'=>$request->new_proposal_number
        ])->first();
        // If number already existing in the database, create new proposal number
        if($validate_number != null){
            $proposal_number_status = 'occupied';
        }else{
            $proposal_number_status = 'available';
        }
        return response()->json([
            'proposal_number_status'=>$proposal_number_status
        ]);
    }

    /**
     * @api - POST
     * @method store // New Proposal
     * @param CreateProposalRequest $request
     * @return JsonResponse
     */
    public function store(CreateProposalRequest $request): JsonResponse
    {
            $user = Auth::user();
            $create_proposal = Proposal::create([
                'adjustments'=>$request->adjustments,
                'prefix'=>$request->proposal_number_prefix,
                'assigned_to'=>$request->assigned_to,
                'currency_id'=>$request->currency_id,
                'discount_value'=>$request->discount_value,
                'lead_customer_id'=>$request->lead_customer_id,
                'message'=>$request->message,
                'proposal_number'=>$request->new_proposal_number,
                'open_till_date'=>$request->open_till_date,
                'proposal_date'=>$request->proposal_date,
                'relation'=>$request->relation,
                'selected_products'=>json_encode($request->selected_products),
                'status'=>json_encode($request->status),
                'sub_total'=>$request->sub_total,
                'subject'=>$request->subject,
                'discount_type_selected'=>$request->discount_type_selected,
                'discount_percentage'=>$request->discount_percentage,
                'total_amount'=>$request->total_amount,
                'total_tax'=>$request->total_tax,
                'created_by_id'=>$user->id,
            ]);

            if ($request->send_email != null) {
                return $this->mailToClient($create_proposal);
            }
            if($create_proposal){
                return response()->json([
                        'message' => __('Proposal submitted successfully!'),
                        'alert' => 'success',
                        'code' => 200
                ]);
            }else{
                return response()->json([
                    'message' => __('Proposal submission failed! please refresh the page and try again'),
                    'alert-type' => 'failed'
                ]);
            }
    }

    /**
     * @api - GET
     * @method statusList // Proposal's status list
     * @return JsonResponse
     */
    public function statusList(): JsonResponse
    {
        $status_list = [
            [ 'id'=>1, 'name'=>'Draft' ],
            [ 'id'=>2, 'name'=>'Sent' ],
            [ 'id'=>3, 'name'=>'Open' ],
            [ 'id'=>4, 'name'=>'Revised' ],
            [ 'id'=>5, 'name'=>'Declined' ],
            [ 'id'=>6, 'name'=>'Accepted' ],
        ];
        return response()->json($status_list);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @api - POST
     * @method getEditProposalData // Proposal's status list
     */
    public function getEditProposalData(Request $request): JsonResponse
    {
        $proposal = Proposal::where(['id'=>$request->id])->with(['currency','user'])->first();
        $selected_product_ids = [];
        foreach (json_decode($proposal->selected_products) as $product) {
            array_push($selected_product_ids, $product->product_id);
        }
        $products = Product::whereIn('id' ,$selected_product_ids)->orderBy('id','desc')->get();
        // return response()->json([json_decode($proposal->selected_products), $selected_product_ids, $products]);

        if($proposal->relation === 'Lead'){
            $lead_customer = Lead::select([
                    'id',
                    'first_name as client_name',
                    'email as client_email',
                ])
                ->where(['id'=>$proposal->lead_customer_id])->first();
        }else{
            $lead_customer = Contact::select([
                    'id',
                    'first_name as client_name',
                    'email as client_email'
                ])
                ->where(['customer_id'=>$proposal->lead_customer_id])->first();
        }

        if($proposal){
            return response()->json([
                'message'=>'Success',
                'code'=>200,
                'proposal'=>$proposal,
                'lead_customer'=>$lead_customer, 
                'products'=>$products ?? null
            ]);
        }else{
            return response()->json([
                'message'=>'Failed',
                'code'=>403
            ]);
        }
    }

        /**
     * @api - POST
     * @method update // Update Proposal
     * @param CreateProposalRequest $request
     * @return JsonResponse
     */
    public function update(CreateProposalRequest $request): JsonResponse
    {
        $proposal = Proposal::where(['id'=>$request->proposal_id])->first();
//        return response()->json(['prp'=>$proposal,$request->all()]);
        $user = Auth::user();
        $proposal->adjustments = $request->adjustments;
        $proposal->prefix = $request->proposal_number_prefix;
        $proposal->assigned_to = $request->assigned_to;
        $proposal->currency_id = $request->currency_id;
        $proposal->discount_value = $request->discount_value;
        $proposal->lead_customer_id = $request->lead_customer_id;
        $proposal->message = $request->message;
        $proposal->proposal_number = $request->new_proposal_number;
        $proposal->open_till_date = $request->open_till_date;
        $proposal->proposal_date = $request->proposal_date;
        $proposal->relation = $request->relation;
        $proposal->selected_products = json_encode($request->selected_products);
        $proposal->status = json_encode($request->status);
        $proposal->sub_total = $request->sub_total;
        $proposal->subject = $request->subject;
        $proposal->discount_type_selected = $request->discount_type_selected;
        $proposal->discount_percentage = $request->discount_percentage;
        $proposal->total_amount = $request->total_amount;
        $proposal->total_tax = $request->total_tax;
        $proposal->created_by_id = $user->id;

//        if ($request->send_email != null) {
//            return $this->mailToClient($create_proposal);
//        }
        if($proposal->save()){
            return response()->json([
                    'message' => __('Proposal updated successfully!'),
                    'alert' => 'success',
                    'code' => 200
            ]);
        }else{
            return response()->json([
                'message' => __('Proposal updation failed! please refresh the page and try again'),
                'alert-type' => 'failed'
            ]);
        }
    }
}
