<?php

namespace App\Http\Controllers;


use App\Models\Target;
use App\Models\Teammaster;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Carmodel;
use App\Models\Branch;
use App\Models\Fuletype;
use Carbon\Carbon;
use App\Exports\ExportTarget;
use App\Imports\ImportTarget;
use Maatwebsite\Excel\Facades\Excel;



use DB, Validator, DataTables;

class TargetController extends Controller
{
    public function __construct(){

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

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

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

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

    }
        
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Target::select(
                    'target.*',
                    'Team_master.team_name as team_name',
                    'branches.name as location_name',
                    'car_model.name as model_name',
                    'fule_type.title as fule_type',
                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name"),
                    DB::raw("DATE_FORMAT(target.date, '%Y-%m') as formated_date")
                )
                ->leftJoin('users', 'users.id', '=', 'target.kec_name')
                ->leftJoin('Team_master', 'Team_master.id', '=', 'target.team_id')
                ->leftJoin('car_model', 'target.model', '=', 'car_model.id')
                ->leftJoin('branches', 'branches.id', '=', 'target.branch')
                ->leftJoin('fule_type', 'fule_type.id', '=', 'target.fuel_type')
                ->groupBy('target.id')
                ->orderBy('target.id', 'desc');
    
            return DataTables::of($data)
                ->editColumn('date', function($data) {
                        return (!empty($data->date))
                            ? \Carbon\Carbon::parse($data->date)->format('F,Y')
                            : '--';
                    })
                ->addColumn('action', function ($row) {
                    $id = base64_encode($row->id);
    
                    return '
                        <a href="javascript:void(0);" class="editInquiry" data-id="' . $id . '" title="Edit">
                            <i class="fa fa-edit text-secondary mx-1"></i>
                        </a>
                        <a href="javascript:void(0);" class="viewInquiry" data-id="' . $id . '" title="View">
                            <i class="fa fa-eye text-secondary mx-1"></i>
                        </a>
                        <a href="javascript:void(0);" class="deleteInquiry" data-id="' . $id . '" title="Delete">
                            <i class="fa fa-trash text-secondary mx-1"></i>
                        </a>';
                })
                ->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('target.date', [$start, $end]);
                    //         } catch (\Exception $e) {
                    //             \Log::error('Invalid date range format for date filter', [
                    //                 'input' => $dateRange,
                    //                 'error' => $e->getMessage()
                    //             ]);
                    //         }
                    //     }
                    // }
                    
                    if ($date = request()->get('date', false)) {
                        $start = \Carbon\Carbon::createFromFormat('Y-m', trim($date))
                        ->startOfMonth()
                        ->format('Y-m-d');
    
                        $end = \Carbon\Carbon::createFromFormat('Y-m', trim($date))
                                    ->endOfMonth()
                                    ->format('Y-m-d');
                
                        $query->whereBetween('target.date', [$start, $end]);
                    }
                
                    if (request()->get('branch',false)) {
                        $query->where('branches.name', "like", "%".request()->get("branch")."%");
                    }
                    if (request()->get('model',false)) {
                        $query->where('car_model.name', "like", "%".request()->get("model")."%");
                    }
                    if (request()->get('fuel_type',false)) {
                        $query->where('fule_type.title', "like", "%".request()->get("fuel_type")."%");
                    }
                    if (request()->get('team_id',false)) {
                        $query->where('Team_master.team_name', "like", "%".request()->get("team_id")."%");
                    }
                    if (request()->get('sales_person_name',false)) {
                        $salesPersonName = request()->get('sales_person_name');
                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$salesPersonName}%"]);
                    }
                })
                ->make(true);
        }
    
        // View data for filter dropdowns
        $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();
        $branch = Branch::select('name', 'id')->where('status', 'active')->get();
        $fuel_type = Fuletype::where('status', 'active')->get();
    
        return view('target.index', compact('teams', 'kecs', 'product', 'branch', 'fuel_type'));
    }


    public function insert(Request $request)
    {
        try {
            $currentTimestamp = now();
            $userId = auth()->id();
    
            $validated = $request->validate([
                'target_type'    => 'required|in:wholesale,retail',
                'date'           => 'required|date_format:Y-m',
                'branch'         => 'required|exists:branches,id',
                'model'          => 'required|exists:car_model,id',
                'fuel_type'      => 'required|exists:fule_type,id',
                'target_value'   => 'required|numeric|min:1',
                /*'team_id'        => 'required_if:target_type,retail|nullable|exists:Team_master,id',
                'kec_name'       => 'required_if:target_type,retail|nullable|exists:users,id'*/
                'team_id'        => 'nullable|exists:Team_master,id',
                'kec_name'       => 'nullable|exists:users,id'
            ]);
            
            $formattedDate = $validated['date'] . '-01'; // used because easy sorting and filetring
            $inquiryData = [
                'date'          => $formattedDate,
                'branch'        => $validated['branch'],
                'target_type'   => $validated['target_type'],
                'model'         => $validated['model'],
                'fuel_type'     => $validated['fuel_type'],
                'target_value'  => $validated['target_value'],
                /*'team_id'       => (isset($validated['team_id']) && $validated['target_type'] == Target::RETAIL) ? $validated['team_id'] : null, 
                'kec_name'      => (isset($validated['kec_name']) && $validated['target_type'] == Target::RETAIL) ? $validated['kec_name'] : null,*/
                'team_id' => ($validated['target_type'] == Target::RETAIL) ? ($validated['team_id'] ?? null) : null,
                'kec_name' => ($validated['target_type'] == Target::RETAIL) ? ($validated['kec_name'] ?? null) : null,
                'created_at'    => $currentTimestamp,
                'created_by'    => $userId,
                'updated_at'    => $currentTimestamp,
                'updated_by'    => $userId,
            ];
           
            DB::beginTransaction();
    
            if ($request->encoded_id) {
                $id = base64_decode($request->encoded_id);
                Target::where('id', $id)->update($inquiryData);
            } else {
                // Insert
                $inquiryData['created_at'] = $currentTimestamp;
                $inquiryData['created_by'] = $userId;
                Target::create($inquiryData);
            }
    
            DB::commit();
    
            return response()->json([
                'success' => true,
                'message' => $request->encoded_id ? 'Target updated successfully.' : 'Target created successfully.',
            ]);
    
        } catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            \Log::error('Target Insert Error: ' . $e->getMessage());
    
            return response()->json([
                'success' => false,
                'message' => 'Insert failed: ' . $e->getMessage(),
            ], 500);
        }
    }
    
    public function edit($id)
    {
        $decodedId = base64_decode($id);
        $data = Target::find($decodedId);
        
        if (!$data) {
            return response()->json([
                'success' => false,
                'message' => 'Target not found.'
            ]);
        }
    
        return response()->json([
            'success' => true,
            'data' => $data
        ]);

    }
    
    public function view($id)
    {
        try {
            $decodedId = base64_decode($id, true);
    
            if (!$decodedId || !is_numeric($decodedId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid ID.'
                ]);
            }
    
            $target = Target::leftJoin('branches', 'target.branch', '=', 'branches.id')
                ->leftJoin('car_model', 'target.model', '=', 'car_model.id')
                ->leftJoin('fule_type', 'target.fuel_type', '=', 'fule_type.id')
                ->leftJoin('Team_master', 'target.team_id', '=', 'Team_master.id')
                ->leftJoin('users', 'target.kec_name', '=', 'users.id')
                ->select(
                    'target.date',
                    'target.target_value',
                    'target.target_type',
                    'branches.name as branch_name',
                    'car_model.name as model_name',
                    'fule_type.title as fuel_type_name',
                    'Team_master.team_name',
                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) as kec_name")
                )
                ->where('target.id', $decodedId)
                ->first();
    
            if (!$target) {
                return response()->json([
                    'success' => false,
                    'message' => 'Target not found.'
                ]);
            }
            
            $target->date = Carbon::parse($target->date)->format('F, Y');
            
            return response()->json([
                'success' => true,
                'data' => $target
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Server error: ' . $e->getMessage()
            ]);
        }
    }
    
   public function delete(Request $request)
    {
        try {
            $encodedId = $request->input('id');
            $decodedId = base64_decode($encodedId, true);
    
            if (!$decodedId || !is_numeric($decodedId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid ID.'
                ]);
            }
    
            $target = Target::find($decodedId);
    
            if (!$target) {
                return response()->json([
                    'success' => false,
                    'message' => 'Target not found.'
                ]);
            }
    
            $target->delete();
    
            return response()->json([
                'success' => true,
                'message' => 'Target deleted successfully.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Server error: ' . $e->getMessage()
            ]);
        }
    }
    
    public function getTeams($branch_id)
    {
        try {
            $teams = Teammaster::select('id', 'team_name')
                ->where('branch_name', $branch_id)
                ->where('status',Teammaster::ACTIVE)
                ->orderBy('team_name')
                ->get();
    
            return response()->json([
                'status' => true,
                'data' => $teams
            ]);
    
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    
    public function getKecs($team_id)
    {
        try {
            $teams = User::select('users.id', DB::raw("CONCAT(users.first_name, ' ', users.last_name) as kec_name"))
                    ->where('team_name', $team_id)
                    ->orderBy('users.first_name')
                    ->get();
            
            return response()->json([
                'status' => true,
                'data' => $teams
            ]);
    
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    
    public function import(Request $request){
        if(Excel::import(new ImportTarget, $request->file('file')->store('file'))){
            return redirect()->route('target')->with('sucess' ,'File Imported Sucessfully');
        }else{
            return redirect()->route('target')->with('error' ,'Faild To Import File!');
        }
    }

    public function export(Request $request){
        if(isset($request->slug) && $request->slug != null){
            $slug = $request->slug;
        }else{
            $slug = 'all';
        }

        $name = 'Target_'.Date('YmdHis').'.xlsx';
    
        try {
            return Excel::download(new ExportTarget($slug), $name);
        }catch(\Exception $e){
            return redirect()->back()->with('error' ,$e->getMessage());
        }
    }
    

}
