<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\DB;

use App\Models\Province;
use App\Models\RoadUpgradeSafety;
use App\Models\RoadDangerPrevention;
use App\Models\RoadConstructionRural;
use App\Models\RoadTechnicalBuilding;
use App\Models\RoadMaintenanceProject;
use App\Models\RoadTollhouseManagement;
use App\Models\RoadItemsProject;
use App\Models\ContractSubItems;
use App\Models\Contracts;

class BamaController extends Controller
{

    public function index()
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1012);
        }
        return view('rmto-preview.pages.BamaRefactor');
    }

    public function homepage_report()
    {
        $collection = ContractSubItems::groupBy('project_type_id')
                                            ->select('project_type_id as id', 'project_type_fa as label')
                                            ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }
    
    
        $data = DB::table('contract_subitems')
                        ->groupBy('project_type_id')
                        ->select('project_type_id as id', 'project_type_fa as label', DB::raw('count(*) as count'))
                        ->get();
    
        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }
            
            
        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            $finalArray['label'][] = $value;
            $finalArray['data'][] = $array['data'][$index];
        }

        $type_sperate = $finalArray;
    
        $collection = ContractSubItems::groupBy('last_status_id')
                                            ->where('last_status_id', '!=', '0')
                                            ->select('last_status_id as id', 'last_status_fa as label')
                                            ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }
    
    
        $data = DB::table('contract_subitems')
                        ->where('last_status_id', '!=', '0')
                        ->groupBy('last_status_id')
                        ->select('last_status_id as id', 'last_status_fa as label', DB::raw('count(*) as count'))
                        ->get();
    
        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }
    
        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            $finalArray['label'][] = $value;
            $finalArray['data'][] = $array['data'][$index];
        }
    
        $status_sperate = $finalArray;

        return response()->json([
                'status' => 'succeed',
                'message' => '',
                'type_sperate' => $type_sperate,
                'status_sperate' => $status_sperate,
                'count_all' => ContractSubItems::count(),
            ], 200);
    }

    public function indexformap(Request $request)
    {
        /// Variables From Queries parameters
        $projectType = $request->project_type;
        $province = $request->province;
        $axis = $request->axis;
        $lastStatus = $request->last_status;
        $fromDate = $request->from_date;
        $toDate = $request->to_date;
        $priority = $request->priority;
        $followup_priority_project_id = $request->followup;
        /// Query to get datas
        $projectsData = ContractSubItems::select('id', 'start_lat', 'start_lng', 'project_type_id')
                                        ->when($projectType, function ($query, $projectType) {
                                            return $query->whereIn('project_type_id', $projectType);
                                        })
                                        ->when($province, function ($query, $province) {
                                            return $query->whereIn('province_id', $province);
                                        })
                                        ->when($axis, function ($query, $axis) {
                                            return $query->whereIn('axis_type_id', $axis);
                                        })
                                        ->when($followup_priority_project_id, function ($query, $followup_priority_project_id) {
                                            return $query->whereIn('followup_priority_project_id', $followup_priority_project_id);
                                        })
                                        ->when($lastStatus, function ($query, $lastStatus) {
                                            return $query->whereIn('last_status_id', $lastStatus);
                                        })
                                        ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                            return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                        })
                                        ->when($priority, function ($query, $priority) {
                                            return $query->whereIn('priority_project', $priority);
                                        })
                                        ->get();

        return response()->json([
            'message' => 'success',
            'data' => $projectsData,
        ], 200);
    }

    public function show(Request $request)
    {

        /// Variables From Queries parameters
        $projectType = $request->project_type;
        $province = $request->province;
        $city = $request->city;
        $axis = $request->axis;
        $lastStatus = $request->last_status;
        $fromDate = $request->from_date;
        $toDate = $request->to_date;
        $priority = $request->priority;
        $followup_priority_project_id = $request->followup;

        /// Query to get datas
        $projectsData = ContractSubItems::select('id', 'last_status_fa', 'project_title', 'province_fa', 'city_fa', 'contract_date_from_parent_contract', 'axis_name_fa', 'image_path1', 'project_type_fa', 'project_type_id')
                                        ->when($projectType, function ($query, $projectType) {
                                            return $query->where('project_type_id', $projectType);
                                        })
                                        ->when($province, function ($query, $province) {
                                            return $query->where('province_id', $province);
                                        })
                                        ->when($city, function ($query, $city) {
                                            return $query->where('city_id', $city);
                                        })
                                        ->when($axis, function ($query, $axis) {
                                            return $query->where('axis_type_id', $axis);
                                        })
                                        ->when($followup_priority_project_id, function ($query, $followup_priority_project_id) {
                                            return $query->where('followup_priority_project_id', $followup_priority_project_id);
                                        })
                                        ->when($lastStatus, function ($query, $lastStatus) {
                                            return $query->where('last_status_id', $lastStatus);
                                        })
                                        ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                            return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                        })
                                        ->when($priority, function ($query, $priority) {
                                            return $query->where('priority_project', $priority);
                                        })
                                        ->paginate();
        
        $projectsCount = count($projectsData);

        $projectsCountByTypes = self::projectsCountByQuery('project_type_id', 'project_type_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByProvinces = self::projectsCountByQuery('province_id', 'province_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByCities = self::projectsCountByQuery('city_id', 'city_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByAxisTypes = self::projectsCountByQuery('axis_type_id', 'axis_type_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByLastStatuses = self::projectsCountByQuery('last_status_id', 'last_status_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByPriority = self::projectsCountByQuery('priority_project', 'priority_project_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByFollowupPriority = self::projectsCountByQuery('followup_priority_project_id', 'followup_priority_project', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);

        $count1400Projects = self::projectsCountByYear('2021-03-21 00:00:00', '2022-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1399Projects = self::projectsCountByYear('2020-03-21 00:00:00', '2021-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1398Projects = self::projectsCountByYear('2019-03-21 00:00:00', '2020-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1397Projects = self::projectsCountByYear('2018-03-21 00:00:00', '2019-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1396Projects = self::projectsCountByYear('2017-03-21 00:00:00', '2018-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1395Projects = self::projectsCountByYear('2016-03-21 00:00:00', '2017-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
 
        return response()->json([
            'message' => 'success',
            'data' => $projectsData,
            'counts' => [
                'projects' => $projectsCount,
                'projectTypes' => $projectsCountByTypes,
                'provinces' => $projectsCountByProvinces,
                'cities' => $projectsCountByCities,
                'axis_types' => $projectsCountByAxisTypes,
                'last_statuses' => $projectsCountByLastStatuses,
                'priorities' => $projectsCountByPriority,
                'followup_priority' => $projectsCountByFollowupPriority,
                'years' => [
                    '1400' => $count1400Projects ?? 0,
                    '1399' => $count1399Projects ?? 0,
                    '1398' => $count1398Projects ?? 0,
                    '1397' => $count1397Projects ?? 0,
                    '1396' => $count1396Projects ?? 0,
                    '1395' => $count1395Projects ?? 0
                ]
            ]
        ], 200);
    }

    public function showList(Request $request)
    {

        /// Variables From Queries parameters
        $projectType = $request->project_type;
        $province = $request->province;
        $city = $request->city;
        $axis = $request->axis;
        $lastStatus = $request->last_status;
        $fromDate = $request->from_date;
        $toDate = $request->to_date;
        $priority = $request->priority;
        $followup_priority_project_id = $request->followup;

        /// Query to get datas
        $projectsData = ContractSubItems::select('id', 'last_status_fa', 'project_title', 'province_fa', 'city_fa', 'contract_date_from_parent_contract', 'axis_name_fa', 'image_path1', 'project_type_fa', 'project_type_id')
                                        ->when($projectType, function ($query, $projectType) {
                                            return $query->where('project_type_id', $projectType);
                                        })
                                        ->when($province, function ($query, $province) {
                                            return $query->where('province_id', $province);
                                        })
                                        ->when($city, function ($query, $city) {
                                            return $query->where('city_id', $city);
                                        })
                                        ->when($axis, function ($query, $axis) {
                                            return $query->where('axis_type_id', $axis);
                                        })
                                        ->when($followup_priority_project_id, function ($query, $followup_priority_project_id) {
                                            return $query->where('followup_priority_project_id', $followup_priority_project_id);
                                        })
                                        ->when($lastStatus, function ($query, $lastStatus) {
                                            return $query->where('last_status_id', $lastStatus);
                                        })
                                        ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                            return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                        })
                                        ->when($priority, function ($query, $priority) {
                                            return $query->where('priority_project', $priority);
                                        })
                                        ->get();
        
        $projectsCount = count($projectsData);

        $projectsCountByTypes = self::projectsCountByQuery('project_type_id', 'project_type_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByProvinces = self::projectsCountByQuery('province_id', 'province_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByCities = self::projectsCountByQuery('city_id', 'city_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByAxisTypes = self::projectsCountByQuery('axis_type_id', 'axis_type_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByLastStatuses = self::projectsCountByQuery('last_status_id', 'last_status_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByPriority = self::projectsCountByQuery('priority_project', 'priority_project_fa', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);
        $projectsCountByFollowupPriority = self::projectsCountByQuery('followup_priority_project_id', 'followup_priority_project', $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id);

        $count1402Projects = self::projectsCountByYear('2023-03-21 00:00:00', '2024-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1401Projects = self::projectsCountByYear('2022-03-21 00:00:00', '2023-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1400Projects = self::projectsCountByYear('2021-03-21 00:00:00', '2022-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1399Projects = self::projectsCountByYear('2020-03-21 00:00:00', '2021-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1398Projects = self::projectsCountByYear('2019-03-21 00:00:00', '2020-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1397Projects = self::projectsCountByYear('2018-03-21 00:00:00', '2019-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1396Projects = self::projectsCountByYear('2017-03-21 00:00:00', '2018-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
        $count1395Projects = self::projectsCountByYear('2016-03-21 00:00:00', '2017-03-20 23:59:50', $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate);
 
        return response()->json([
            'message' => 'success',
            'data' => $projectsData,
            'counts' => [
                'projects' => $projectsCount,
                'projectTypes' => $projectsCountByTypes,
                'provinces' => $projectsCountByProvinces,
                'cities' => $projectsCountByCities,
                'axis_types' => $projectsCountByAxisTypes,
                'last_statuses' => $projectsCountByLastStatuses,
                'priorities' => $projectsCountByPriority,
                'followup_priority' => $projectsCountByFollowupPriority,
                'years' => [
                    '1402' => $count1402Projects ?? 0,
                    '1401' => $count1401Projects ?? 0,
                    '1400' => $count1400Projects ?? 0,
                    '1399' => $count1399Projects ?? 0,
                    '1398' => $count1398Projects ?? 0,
                    '1397' => $count1397Projects ?? 0,
                    '1396' => $count1396Projects ?? 0,
                    '1395' => $count1395Projects ?? 0
                ]
            ]
        ], 200);
    }

    public function projectsCountByQuery($id, $fa, $province, $city, $axis, $lastStatus, $fromDate, $priority, $toDate, $projectType, $followup_priority_project_id)
    {
        $count = ContractSubItems::select($id, $fa, DB::raw('count(*) as count'))
                                ->when($projectType, function ($query, $projectType) {
                                    return $query->where('project_type_id', $projectType);
                                })
                                ->when($province, function ($query, $province) {
                                    return $query->where('province_id', $province);
                                })
                                ->when($city, function ($query, $city) {
                                    return $query->where('city_id', $city);
                                })
                                ->when($axis, function ($query, $axis) {
                                    return $query->where('axis_type_id', $axis);
                                })
                                ->when($lastStatus, function ($query, $lastStatus) {
                                    return $query->where('last_status_id', $lastStatus);
                                })
                                ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                    return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                })
                                ->when($priority, function ($query, $priority) {
                                    return $query->where('priority_project', $priority);
                                })
                                ->when($followup_priority_project_id, function ($query, $followup_priority_project_id) {
                                    return $query->where('followup_priority_project_id', $followup_priority_project_id);
                                })
                                ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                    return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                })
                                ->groupBy($id)
                                ->get();
        return $count;
    }

    public function projectsCountByYear($dateFrom, $dateTo, $province, $city, $axis, $lastStatus, $priority, $projectType, $fromDate, $toDate)
    {
        $count = ContractSubItems::whereBetween('contract_date_from_parent_contract', [$dateFrom, $dateTo])
                                            ->when($projectType, function ($query, $projectType) {
                                                return $query->where('project_type_id', $projectType);
                                            })
                                            ->when($province, function ($query, $province) {
                                                return $query->where('province_id', $province);
                                            })
                                            ->when($city, function ($query, $city) {
                                                return $query->where('city_id', $city);
                                            })
                                            ->when($axis, function ($query, $axis) {
                                                return $query->where('axis_type_id', $axis);
                                            })
                                            ->when($lastStatus, function ($query, $lastStatus) {
                                                return $query->where('last_status_id', $lastStatus);
                                            })
                                            ->when($priority, function ($query, $priority) {
                                                return $query->where('priority_project', $priority);
                                            })
                                            ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                                return $query->whereBetween('contract_date_from_parent_contract', [$fromDate, $toDate]);
                                            })
                                            ->count();
        return $count;
    }

    public function getSingleData(Request $request, $id)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1014);
        }
        $contractSubItem = ContractSubItems::find($id);

        if (!$contractSubItem) {
            return response()->json([
                'message' => 'Data not found'
            ], 404);
        }

        $array = [];
        
        $array = [
                
                'required_bitumen' => $contractSubItem->required_bitumen,
                'used_bitumen' => $contractSubItem->used_bitumen,
                'bridge_number' => $contractSubItem->bridge_number,
                'contract_number' => $contractSubItem->contract_number,
                'contract_date' => $contractSubItem->contract_date,
                'unique_code' => $contractSubItem->unique_code,
                'progress_project' => $contractSubItem->progress_project,
                'province_fa' => $contractSubItem->province_fa,
                'city_fa' => $contractSubItem->city_fa,
                'project_type_fa' => $contractSubItem->project_type_fa,
                'project_type_id' => $contractSubItem->project_type_id,
                'project_title' => $contractSubItem->project_title,
                'axis_type_fa' => $contractSubItem->axis_type_fa,
                'axis_name_fa' => $contractSubItem->axis_name_fa,
                'last_status_fa' => $contractSubItem->last_status_fa,
                'created_at_fa' => $contractSubItem->created_at_fa,
                'created_at' => $contractSubItem->created_at,
                'updated_at_fa' => $contractSubItem->updated_at_fa,
                'updated_at' => $contractSubItem->last_date_update,
                'operator_name' => $contractSubItem->operator_name,
                'operator_phone' => $contractSubItem->operator_phone,
                'last_digit_project' => $contractSubItem->last_digit_project,
                'last_function_operator' => $contractSubItem->last_function_operator,
                'last_payable_operator' => $contractSubItem->last_payable_operator,
                'complete_payable' => $contractSubItem->complete_payable,
                'start_lat' => $contractSubItem->start_lat,
                'end_lat' => $contractSubItem->end_lat,
                'start_lng' => $contractSubItem->start_lng,
                'end_lng' => $contractSubItem->end_lng,
                'priority_project_fa' => $contractSubItem->priority_project_fa,
                'followup_priority_project' => $contractSubItem->followup_priority_project,
                'image_path1' => $contractSubItem->image_path1,
                'image_path2' => $contractSubItem->image_path2,
                'contract' => $contractSubItem->Contracts,
                'operation' => [
                    [
                        'hasOperation' => $contractSubItem->operation_type_id1 != 0 ? 1 : 0,
                        'operation_type_id1' => $contractSubItem->operation_type_id1,
                        'operation_type_fa1' => $contractSubItem->operation_type_fa1,
                        'operation_type_unit1' => $contractSubItem->operation_type_unit1 ?? '-',
                        'operation_type_amount1' => $contractSubItem->operation_type_amount1,
                        'operation_type_progress1' => $contractSubItem->operation_type_progress1,
                        'operation_type_tonaj1' => $contractSubItem->operation_type_tonaj1 ?? '-',
                    ],
                    [
                        'hasOperation' => $contractSubItem->operation_type_id2 != 0 ? 1 : 0,
                        'operation_type_id2' => $contractSubItem->operation_type_id2,
                        'operation_type_fa2' => $contractSubItem->operation_type_fa2,
                        'operation_type_unit2' => $contractSubItem->operation_type_unit2 ?? '-',
                        'operation_type_amount2' => $contractSubItem->operation_type_amount2,
                        'operation_type_progress2' => $contractSubItem->operation_type_progress2,
                        'operation_type_tonaj2' => $contractSubItem->operation_type_tonaj2 ?? '-',
                    ],
                    [
                        'hasOperation' => $contractSubItem->operation_type_id3 != 0 ? 1 : 0,
                        'operation_type_id3' => $contractSubItem->operation_type_id3,
                        'operation_type_fa3' => $contractSubItem->operation_type_fa3,
                        'operation_type_unit3' => $contractSubItem->operation_type_unit3 ?? '-',
                        'operation_type_amount3' => $contractSubItem->operation_type_amount3,
                        'operation_type_progress3' => $contractSubItem->operation_type_progress3,
                        'operation_type_tonaj3' => $contractSubItem->operation_type_tonaj3 ?? '-',
                    ],
                    [
                        'hasOperation' => $contractSubItem->operation_type_id4 != 0 ? 1 : 0,
                        'operation_type_id4' => $contractSubItem->operation_type_id4,
                        'operation_type_fa4' => $contractSubItem->operation_type_fa4,
                        'operation_type_unit4' => $contractSubItem->operation_type_unit4 ?? '-',
                        'operation_type_amount4' => $contractSubItem->operation_type_amount4,
                        'operation_type_progress4' => $contractSubItem->operation_type_progress4,
                        'operation_type_tonaj4' => $contractSubItem->operation_type_tonaj ?? -4
                    ]
                ]
            ];

        return response()->json([
            'message' => 'success',
            'data' => $array
        ], 200);
    }

    public function getAllProjectTypes(Request $request)
    {
        $data = ContractSubItems::groupBy('project_type_id')
                                ->select('project_type_id as id', 'project_type_fa_for_chart as label')
                                ->get();
        
        return response()->json([
            'message' => 'success',
            'data' => $data
        ], 200);
    }
}