<?php

namespace App\Http\Controllers;


use App\Models\InquiryForm;
use App\Models\Teammaster;
use Illuminate\Http\Request;
use App\Models\State;
use App\Models\InquiryFollowUp;
use App\Models\City;
use App\Models\User;
use App\Models\Carmodel;
use Carbon\Carbon;
use App\Models\Lead;
use App\Models\Branch;
use App\Models\Sublead;

use DB, Validator, DataTables;

class InquiryFormController extends Controller
{
    public function __construct(){

        $this->middleware('permission:inquiry-create', ['only' => ['create']]);

        $this->middleware('permission:inquiry-edit', ['only' => ['edit']]);

        $this->middleware('permission:inquiry-view', ['only' => ['view']]);

        $this->middleware('permission:inquiry-delete', ['only' => ['delete']]);

    }
        
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = InquiryForm::select(
                    'inquiry_form.id', 
                    'inquiry_form.customer_name', 
                    DB::raw("DATE_FORMAT(inquiry_form.date, '%d-%m-%Y') as formatted_date"),
                    'inquiry_form.date',
                    'inquiry_form.model',
                    'inquiry_form.location',
                    'inquiry_form.lead_source',
                    'inquiry_form.sub_lead_source',
                    'inquiry_form.email',
                    'inquiry_form.contact',
                    'Team_master.team_name',
                    'common_state.name as state',
                    'city.name as city',
                    'lead.name as lead_source_name',
                    'sub_lead.name as sub_lead_source_name',
                    'branches.name as location_name',
                    'car_model.name as model_name',
                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name")
                )
                ->leftjoin('users','users.id','=','inquiry_form.assigned_kec')
                ->leftJoin('Team_master', 'Team_master.id', '=', 'inquiry_form.assigned_tl')
                ->leftjoin('car_model', 'inquiry_form.model', 'car_model.id')
                ->leftjoin('branches','branches.id','=','inquiry_form.location')
                ->leftjoin('lead','lead.id','=','inquiry_form.lead_source')
                ->leftjoin('sub_lead','sub_lead.id','=','inquiry_form.sub_lead_source')
                ->leftJoin('common_state', 'common_state.id', '=', 'inquiry_form.state_id')
                ->leftJoin('city', 'city.id', '=', 'inquiry_form.city_id')
                ->groupBy('inquiry_form.id')
                ->orderBy('inquiry_form.id', 'desc');
    
            return DataTables::of($data)
            ->addColumn('action', function ($row) {
                $id = base64_encode($row->id);
                $return = '';

                // Main edit button
                $return .= '<button type="button" class="btn btn-default btn-xs editInquiry" data-id="' . base64_encode($row->id) . '">
                                <i class="fa fa-edit"></i>
                            </button> &nbsp;';
            
                // Dropdown menu
                $return .= '<div class="btn-group">
                    <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fa fa-bars"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item follow-up" href="javascript:;" data-id="' . $row->id . '">Follow Up</a></li>
                        <li><a class="dropdown-item obf" href="' . route('obf.create') . '">Convert To OBF</a></li>
                    </ul>
                </div>';
            
                return $return;
            })
            ->filter(function ($query){
            if ($dateRange = request()->get('date', false)) {
                $dates = explode(' to ', $dateRange);
                if (count($dates) === 2) {
                    try {
                        $start = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[0]))->startOfDay()->format('Y-m-d');
                        $end = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay()->format('Y-m-d');
                        $query->whereBetween('inquiry_form.date', [$start, $end]);
                    } catch (\Exception $e) {
                        \Log::error('Invalid date range format for date filter', [
                            'input' => $dateRange,
                            'error' => $e->getMessage()
                        ]);
                    }
                }
            }
        
            if ($customer_name = request()->get('customer_name', false)) {
                $query->where('inquiry_form.customer_name', 'like', "%$customer_name%");
            }
        
            if ($email = request()->get('email', false)) {
                $query->where('inquiry_form.email', 'like', "%$email%");
            }
        
            if ($contact = request()->get('contact', false)) {
                $query->where('inquiry_form.contact', 'like', "%$contact%");
            }
        
            if ($state = request()->get('state', false)) {
                $query->where('common_state.name', 'like', "%$state%");
            }
        
            if ($city = request()->get('city', false)) {
                $query->where('city.name', 'like', "%$city%");
            }
        
            if ($lead_source = request()->get('lead_source', false)) {
                $query->where('inquiry_form.lead_source', 'like', "%$lead_source%");
            }
        
            if ($sub_lead_source = request()->get('sub_lead_source', false)) {
                $query->where('inquiry_form.sub_lead_source', 'like', "%$sub_lead_source%");
            }
        
            if ($model = request()->get('model', false)) {
                $query->where('inquiry_form.model', 'like', "%$model%");
            }
        
            if ($location = request()->get('location', false)) {
                $query->where('inquiry_form.location', 'like', "%$location%");
            }
        
            if ($team_name = request()->get('team_name', false)) {
                $query->where('Team_master.team_name', 'like', "%$team_name%");
            }
        
            if ($sales_person_name = request()->get('sales_person_name', false)) {
                $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%$sales_person_name%"]);
            }
        })   
            ->make(true);
        }
    
        $states = State::select('id','name as state_name')->where(['status' => 'active'])->get();
        $cities = City::select('id','name as city_name')->where(['status' => 'active'])->get();
        $teams = DB::table('Team_master')->get();
        $kecs = User::select('users.id',DB::raw("CONCAT(users.first_name, ' ', users.last_name) as kec_name"))->get();
        $product = Carmodel::select('name','id')->where('status','active')->get();
        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $sublead = SubLead::select('id' ,'name')->where(['status' => 'active'])->get();
        $branch = Branch::select('name','id')->where('status','active')->get();

        
        return view('inquiry.index', compact('states', 'cities', 'teams', 'kecs', 'product', 'lead', 'sublead', 'branch'));
    }

    public function insert(Request $request)
    {
        $currentTimestamp = now();
        $userId = auth()->id();
    
        $inquiryData = [
            'date' => $request->date,
            'customer_name' => strtoupper($request->customer_name),
            'lead_source' => $request->lead_source,
            'sub_lead_source' => $request->sub_lead_source,
            'model' => $request->model,
            'email' => $request->email,
            'contact' => $request->contact,
            'location' => $request->location,
            'state_id' => $request->state_id ?? null,
            'city_id' => $request->city_id ?? null,
            'assigned_tl' => $request->assigned_tl ?? null,
            'assigned_kec' => $request->assigned_kec ?? null,
            'updated_at' => $currentTimestamp,
            'updated_by' => $userId,
        ];
    
        DB::beginTransaction();
    
        try {
            if ($request->encoded_id) {
                // Update
                $id = base64_decode($request->encoded_id);
                InquiryForm::where('id', $id)->update($inquiryData);
            } else {
                // Insert
                $inquiryData['created_at'] = $currentTimestamp;
                $inquiryData['created_by'] = $userId;
    
                $id = InquiryForm::insertGetId($inquiryData);
            }
    
            DB::commit();
    
            return response()->json([
                'success' => true,
                'message' => $request->encoded_id ? 'Inquiry updated successfully.' : 'Inquiry created successfully.',
            ]);
        } catch (\Throwable $th) {
            DB::rollBack();
            report($th);
    
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong.',
            ], 500);
        }
    }
    
    public function edit($id)
    {
        $decodedId = base64_decode($id);
        $data = InquiryForm::find($decodedId);
    
        if (!$data) {
            return response()->json([
                'success' => false,
                'message' => 'Inquiry not found.'
            ]);
        }
    
        return response()->json([
            'success' => true,
            'data' => $data
        ]);

    }
    
    public function assign(Request $request)
    {
        
        InquiryFollowUp::create([
            'inquiry_id' => $request->inquiry_id,
            'follow_up_date' => Carbon::parse($request->follow_up_date),
            'next_follow_up_date' => $request->next_follow_up_date ? Carbon::parse($request->next_follow_up_date) : null,
            'remark' => $request->remark,
        ]);
    
        return redirect()->back()->with('success', 'Follow-up saved successfully.');
    }

}
