<?php

namespace App\Http\Controllers;

use App\Models\Contracts;
use App\Models\ContractEblaghMeli;
use App\Models\ContractMojavezSetad;
use App\Models\ContractSubItems;
use App\Models\TarhList;
use App\Models\ContractSubItemsHistory;
use Hekmatinasser\Verta\Verta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\Api\StoreContractRequest;
use App\Http\Controllers\Api\ContractSubItemsController;
use Illuminate\Support\Facades\DB;
use PDF;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;

class ContractsController extends Controller
{
    public function indexForDevelop(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1000);
        }

        if ($request->has('develope')) {
            $fields = ['id', 'province_id', 'province_fa', 'office_fa', 'title', 'status_fa', 'contract_date',
            'national_credit_license','province_credit_license', 'headquarter_issued_license', 'province_issued_license',
            'contract_credit','contract_credit_province', 'contract_credit_national', 'contract_tarh_array',
            'contract_peymankar', 'contract_moshaver_tarahi', 'contract_moshaver_nezarat', 'status_id', 'office_id',
            'unique_id', 'status_rel', 'created_at','contract_number'];

            $contracts = processDataTable($request, Contracts::class, $fields);

            return response()->json(
                $contracts,
                200
            );
        }

        $time_start = microtime(true);
        $fromDate = $request->fromDate ?? null;
        $toDate = $request->toDate ?? null;
        $province = isset($request->province) ? explode(',', $request->province) : null;
        $status = isset($request->status) ? explode(',', $request->status) : null;
        $projectType = $request->projectType ? explode(',', $request->projectType) : null;
        $statusRel = $request->status_rel;

        /// [START] contract_show_data_index
        if (Auth::user()->hasDirectPermission('show-contract')) {
            $temp_data = Contracts::select()
            ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                return $query->whereBetween('contract_date', [$fromDate, $toDate]);
            })
            ->when($province, function ($query) use ($province) {
                return $query->whereIn('province_id', $province);
            })
            ->when($status, function ($query) use ($status) {
                return $query->whereIn('status_id', $status);
            })
            ->when($statusRel, function ($query) use ($statusRel) {
                return $query->where('status_rel', $statusRel);
            })
            ->withCount('subitems')
            ->when($projectType, function ($query) use ($projectType) {
                return $query->whereHas('subitems', function ($query) use ($projectType) {
                    $query->whereIn('project_type_id', $projectType ?? []);
                });
            })
            ->orderBy('id', 'desc')
            ->get();
        } elseif (Auth::user()->hasDirectPermission('show-contract-province')) {
            $temp_data = Contracts::select()
            ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                return $query->whereBetween('contract_date', [$fromDate, $toDate]);
            })
            ->where('province_id', Auth::user()->province_id)
            ->when($status, function ($query) use ($status) {
                return $query->whereIn('status_id', $status);
            })
            ->when($statusRel, function ($query) use ($statusRel) {
                return $query->where('status_rel', $statusRel);
            })
            ->withCount('subitems')
            ->when($projectType, function ($query) use ($projectType) {
                return $query->whereHas('subitems', function ($query) use ($projectType) {
                    $query->whereIn('project_type_id', $projectType ?? []);
                });
            })
            ->orderBy('id', 'desc')
            ->get();
        } else {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }

        /// [END] contract_show_data_index

        $data = [];
        foreach ($temp_data as $key => $item) {
            $exploded_contract_date = explode('-', $item->contract_date);

            /// [START] add-project_data_index
            if (Auth::user()->can('add-project')) {
                $canAddProject = 1;
            } elseif (Auth::user()->can('add-project-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canAddProject = 1;
                } else {
                    $canAddProject = 0;
                }
            } else {
                $canAddProject = 0;
            }
            /// [END] add-project_data_index

            /// [START] contract_edit_data_index
            if (Auth::user()->can('edit-contract')) {
                $canEdit = 1;
            } elseif (Auth::user()->can('edit-contract-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canEdit = 1;
                } else {
                    $canEdit = 0;
                }
            } else {
                $canEdit = 0;
            }
            /// [END] contract_edit_data_index
            /// [START] contract_delete_data_index
            if (Auth::user()->can('delete-contract')) {
                $canDelete = 1;
            } elseif (Auth::user()->can('delete-contract-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } else {
                $canDelete = 0;
            }
            /// [END] contract_delete_data_index
            if (Auth::user()->can('show-project')) {
                $canShowProject = 1;
            } else {
                $canShowProject = 0;
            }
            $data[] = array(
                'id' => $item->id,
                'province_fa' => $item->province_fa,
                'province_id' => $item->province_id,
                'office_fa' => $item->office_fa,
                'title' => $item->title,
                'status_fa' => $item->status_fa,
                'contract_date' => Verta::createJalaliDate($exploded_contract_date[0], $exploded_contract_date[1], $exploded_contract_date[2])->formatGregorian('Y-m-d'),
                'national_credit_license' => $item->national_credit_license,
                'province_credit_license' => $item->province_credit_license,
                'headquarter_issued_license' => $item->headquarter_issued_license,
                'province_issued_license' => $item->province_issued_license,
                'contract_credit' => $item->contract_credit,
                'contract_credit_province' => $item->contract_credit_province,
                'contract_credit_national' => $item->contract_credit_national,
                'contract_tarh_array' => $item->contract_tarh_array,
                'contract_peymankar' => $item->contract_peymankar,
                'contract_moshaver_tarahi' => $item->contract_moshaver_tarahi,
                'contract_moshaver_nezarat' => $item->contract_moshaver_nezarat,
                'created_at_fa' => $item->created_at_fa,
                'created_at' => $item->created_at,
                'unique_id' => $item->unique_id,
                'status_rel' => $item->status_rel,
                'projects_count' => $item->subitems_count,
                'status_id' => $item->status_id,
                'office_id' => $item->office_id,
                'canEdit' => $canEdit,
                'canAddProject' => $canAddProject,
                'canDelete' => $canDelete,
                'canShowProject' => $canShowProject,
                'contract_number' => $item->contract_number,
            );
        }
        $time_end = microtime(true);
        $execution_time = ($time_end - $time_start);

        return response()->json([
            'status' => 'succeed',
            'execution_time' => $execution_time,
            'message' => '',
            'canCrud' => 1,
            'data' => $data,
        ], 200);
    }

    public function index(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1000);
        }

        $fields = ['contracts.id','contracts.province_fa','contracts.province_id','office_fa','title','status_fa',
                   'contract_date','national_credit_license','province_credit_license','headquarter_issued_license','province_issued_license','contract_credit','contract_credit_province','contract_credit_national',
                   'contract_tarh_array','contract_peymankar','contracts.contract_moshaver_tarahi', 'contract_number','contracts.contract_moshaver_nezarat','contracts.created_at_fa','contracts.created_at','unique_id','status_rel',
                   'status_id', 'office_id', 'documents'];

        $aliases = ['', 'province_fa', 'province_id', '', '', '', '', '', '', '', '', '', '', '', '', '', 'contract_moshaver_tarahi', 'contract_number', 'contract_moshaver_nezarat', 'created_at_fa', 'contracts_created_at', '', '', '', '', '', ''];
        $selectRaw = makeSelectQuery($fields, $aliases);

        // add following columns in search but not in select query:
        $fields[] = 'project_type_id';

        if (Auth::user()->can('show-contract')) {
            $query = Contracts::withCount('subitems')
                              ->selectRaw($selectRaw);

        } elseif (Auth::user()->can('show-contract-province')) {
            $query = Contracts::withCount('subitems')
                              ->where('province_id', Auth::user()->province_id)
                              ->selectRaw($selectRaw);
        } else {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }

        $table_results = processDataTable($request, '', $fields, $query, 'subitems');
        $result = [];
        foreach ($table_results['data'] as $key => $item) {
            $exploded_contract_date = explode('-', $item->contract_date);

            /// [START] add-project_data_index
            if (Auth::user()->can('add-project')) {
                $canAddProject = 1;
            } elseif (Auth::user()->can('add-project-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canAddProject = 1;
                } else {
                    $canAddProject = 0;
                }
            } else {
                $canAddProject = 0;
            }
            /// [END] add-project_data_index

            /// [START] contract_edit_data_index
            if (Auth::user()->can('edit-contract')) {
                $canEdit = 1;
            } elseif (Auth::user()->can('edit-contract-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canEdit = 1;
                } else {
                    $canEdit = 0;
                }
            } else {
                $canEdit = 0;
            }
            /// [END] contract_edit_data_index
            /// [START] contract_delete_data_index
            if (Auth::user()->can('delete-contract')) {
                $canDelete = 1;
            } elseif (Auth::user()->can('delete-contract-province')) {
                if ($item->province_id == Auth::user()->province_id) {
                    $canDelete = 1;
                } else {
                    $canDelete = 0;
                }
            } else {
                $canDelete = 0;
            }
            /// [END] contract_delete_data_index
            if (Auth::user()->can('show-project')) {
                $canShowProject = 1;
            } else {
                $canShowProject = 0;
            }

            $result[$key] = $item->toArray();
            $result[$key]['created_at'] = $item->created_at;
            $result[$key]['canEdit'] = $canEdit;
            $result[$key]['canAddProject'] = $canAddProject;
            $result[$key]['canDelete'] = $canDelete;
            $result[$key]['canShowProject'] = $canShowProject;

        }

        return response()->json([
            "draw" => $table_results['draw'],
            "recordsTotal" => $table_results['recordsTotal'],
            "recordsFiltered" => $table_results['recordsFiltered'],
            'data' => $result,
        ], 200);

    }

    public function storeForDevelop(StoreContractRequest $request)
    {

        /// [START] contract_add_data_store
        if (!(Auth::user()->can('add-contract') || (Auth::user()->can('add-contract-province') && $request->province_id == Auth::user()->province_id))) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] contract_add_data_store

        $contract = new Contracts();
        $contract->office_id = $request->office_id;
        $contract->office_fa = $request->office_fa;
        $contract->province_id = $request->province_id;
        $contract->province_fa = \App\Models\Province::where('id', $request->province_id)->first()->name_fa;
        $contract->title = $request->title;
        $contract->status_id = $request->status_id;
        $contract->status_fa = $request->status_fa;
        $contract->contract_date = $request->contract_date;
        $contract->contract_peymankar = $request->contract_peymankar;
        $contract->contract_moshaver_tarahi = $request->contract_moshaver_tarahi;
        $contract->contract_moshaver_nezarat = $request->contract_moshaver_nezarat;

        $contract->national_credit_license = $request->national_credit_license ?? 0;
        $contract->province_credit_license = $request->province_credit_license ?? 0;
        $contract->headquarter_issued_license = $request->headquarter_issued_license ?? 0;
        $contract->province_issued_license = $request->province_issued_license ?? 0;

        $contract->contract_tarh_array = $request->contract_tarh_array;

        $contract->contract_credit = $request->contract_credit;
        $contract->contract_credit_province = $request->contract_credit_province;
        $contract->contract_credit_headquarter = $request->contract_credit_headquarter;
        $contract->contract_credit_national = $request->contract_credit_national;
        $contract->contract_number  = $request->contract_number ?? 0;

        $contract->created_at_fa = Verta::instance(Verta::now());
        $contract->user_id = Auth::user()->id;
        $contract->is_new = 1;
        $contract->save();

        $contract->unique_id = $contract->id + 10000;
        $contract->save();

        // document begin

        $documents = [];
        foreach ($request->documents as $index => $item) {
            $documents[$index]['file'] = $item['file']->store('contract/'. $contract->id . '/' .now()->year . '/documents', 'public');
            $documents[$index]['title'] = $item['title'];
        }
        $contract->documents = serialize($documents);

        $contract->save();
        // document end


        $str = $request->contract_mojavez_data_meli;
        $dat = explode('-', $str);
        $eblagh = ContractEblaghMeli::whereIn('id', $dat)->update(['used' => 1]);

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $contract,
        ], 200);
    }

    public function updateForDevelop(StoreContractRequest $request, $id)
    {
        /// [START] contract_edit_data_update
        if (!(Auth::user()->can('edit-contract') || (Auth::user()->can('edit-contract-province') && $request->province_id == Auth::user()->province_id))) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] contract_edit_data_update

        $contract = Contracts::find($id);
        $contract->office_id = $request->office_id;
        $contract->office_fa = $request->office_fa;
        $contract->province_id = $request->province_id;
        $contract->province_fa = \App\Models\Province::where('id', $request->province_id)->first()->name_fa;
        $contract->title = $request->title;
        $contract->status_id = $request->status_id;
        $contract->status_fa = $request->status_fa;
        $contract->contract_date = $request->contract_date;
        $contract->contract_peymankar = $request->contract_peymankar;
        $contract->contract_moshaver_tarahi = $request->contract_moshaver_tarahi;
        $contract->contract_moshaver_nezarat = $request->contract_moshaver_nezarat;

        $contract->national_credit_license = $request->national_credit_license;
        $contract->province_credit_license = $request->province_credit_license;
        $contract->headquarter_issued_license = $request->headquarter_issued_license;
        $contract->province_issued_license = $request->province_issued_license;

        $contract->contract_tarh_array = $request->contract_tarh_array;

        $contract->contract_credit = $request->contract_credit;
        $contract->contract_credit_province = $request->contract_credit_province;
        $contract->contract_credit_headquarter = $request->contract_credit_headquarter;
        $contract->contract_credit_national = $request->contract_credit_national;
        $contract->contract_number = $request->contract_number ?? 0;

        $contract->save();


        // document begin

        $documents = [];
        $contract_document = $contract->documents != null ? unserialize($contract->documents) : [];
        $index_for_final_array = 0;
        if ($request->has('documents_delete')) {
            foreach ($request->documents_delete as $key => $value) {
                // dd($contract_document[$value]['file']);
                Storage::delete('public/' . $contract_document[$value]['file']);
                unset($contract_document[$value]);
            }
        }

        foreach ($contract_document as $key => $value) {
            $documents[$index_for_final_array]['file'] = $value['file'];
            $documents[$index_for_final_array]['title'] = $value['title'];
            $index_for_final_array++;
        }

        if ($request->has('documents')) {

            foreach ($request->documents as $index => $item) {
                $documents[$index_for_final_array]['file'] = $item['file']->store('contract/'. $contract->id . '/' .now()->year . '/documents', 'public');
                $documents[$index_for_final_array]['title'] = $item['title'];
                $index_for_final_array++;
            }

        }

        $contract->documents = serialize($documents);

        $contract->save();
        // document end

        // for updating sub contract contract date
        foreach ($contract->subitems as $key => $value) {
            $tmp = explode('-', $request->contract_date);
            $tmp = Verta::jalaliToGregorian($tmp[0], $tmp[1], $tmp[2]);
            $value->contract_date_from_parent_contract = $tmp[0].'-'.$tmp[1].'-'.$tmp[2];
            $value->save();
        }

        Auth::user()->addActivity("قرارداد با آیدی {$request->id} بروزرسانی شد.");

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $contract,
        ], 200);
    }

    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:contracts,id'
            ]);

        $roadProject = Contracts::find($request->id);

        /// [START] contract_delete_data_delete
        if (!(Auth::user()->can('delete-contract') || (Auth::user()->can('delete-contract-province') && $roadProject->province_id == Auth::user()->province_id))) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] contract_delete_data_delete

        $subitems = ContractSubItems::where('contract_id', $roadProject->id)->get();

        foreach ($subitems as $item) {
            $subIDs[] = $item->id;
        }

        $histories = ContractSubItemsHistory::whereIn('subitem_id', $subIDs ?? [])->get();
        foreach ($histories as $history) {
            $history->delete();
        }

        $roadProject->subitems()->delete();
        $roadProject->delete();

        Auth::user()->addActivity("قرارداد با آیدی {$request->id} حذف شد.");

        return response()->json([
            'status' => 'succeed',
            'message' => '',
        ], 200);
    }

    public function get_eblagh_meli(Request $request)
    {


        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => TarhList::all(),
        ], 200);
    }

    public function get_mojavez_setad(Request $request)
    {
        /// bayad ba user ostan gerefte shavad va faghat ostan bedahad
        $data = ContractMojavezSetad::where('province_id', Auth::user()->province_id)->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
        ], 200);
    }

    public function document(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1009);
        }
        $getProvinceName = \App\Models\Province::where('id', $request->province)->first()->name_fa;
        foreach ((new ContractSubItemsController())->getAllOperationList() as $key => $value) {
            $summaryProjectsStatusExecute[$key] =
             [
                     'project_type_fa' => $value['farsi'],
                     'project_count' => '0',
                     'AvgProgressProjects' => '0',
             ];
        }
        /// summary projects status
        $summaryProjectsStatus = "SELECT
            project_type_id,
            project_type_fa,
            COUNT(*) as project_count, 
            AVG(progress_project) as AvgProgressProjects 
            FROM contract_subitems
            where province_id = {$request->province}
            GROUP BY project_type_id
            order by project_type_id"
        ;

        foreach (DB::select($summaryProjectsStatus) as $key => $value) {
            $summaryProjectsStatusExecute[$value->project_type_id] = [
                'project_count' => $value->project_count,
                'AvgProgressProjects' => $value->AvgProgressProjects,
            ];
        }

        /// summary projects status
        $summaryProjectsAll = "SELECT
            COUNT(*) as project_count, 
            AVG(progress_project) as AvgProgressProjects 
            FROM contract_subitems
            where province_id = {$request->province}"
        ;

        $summaryProjectsAllExecute = DB::select($summaryProjectsAll);

        /// summary project status by last status
        $summaryProjectsStatusByLastStatus = "SELECT
            COUNT(CASE WHEN project_type_id = 1 THEN 1 END) as MaintananceCount, 
            COUNT(CASE WHEN project_type_id = 2 THEN 1 END) as DangerPointCount,
            COUNT(CASE WHEN project_type_id = 3 THEN 1 END) as RoadUpgradeCount,
            COUNT(CASE WHEN project_type_id = 4 THEN 1 END) as TechnicalCount,
            COUNT(CASE WHEN project_type_id = 5 THEN 1 END) as TollhouseCount,
            COUNT(CASE WHEN project_type_id = 6 THEN 1 END) as VillageRoads,
            last_status_id,
            last_status_fa
            FROM contract_subitems
            WHERE province_id = {$request->province}
            GROUP BY last_status_id"
        ;

        $summaryProjectsStatusByLastStatusExecute = DB::select($summaryProjectsStatusByLastStatus);

        /// project status divide by cities
        $projectsStatusByCities = "SELECT
            COUNT(*) as TotalProjects,
            COUNT(CASE WHEN project_type_id = 1 THEN 1 END) as MaintananceCount, 
            COUNT(CASE WHEN project_type_id = 2 THEN 1 END) as DangerPointCount,
            COUNT(CASE WHEN project_type_id = 3 THEN 1 END) as RoadUpgradeCount,
            COUNT(CASE WHEN project_type_id = 4 THEN 1 END) as TechnicalCount,
            COUNT(CASE WHEN project_type_id = 5 THEN 1 END) as TollhouseCount,
            COUNT(CASE WHEN project_type_id = 6 THEN 1 END) as VillageRoads,
            AVG(progress_project) as avg,
            city_fa
            FROM contract_subitems
            WHERE province_id = {$request->province}
            AND progress_project IS NOT NULL
            GROUP BY city_id"
        ;

        $projectsStatusByCitiesExecute = DB::select($projectsStatusByCities);

        /// important maintanance projects
        $importantMaintananceProjects = "SELECT 
        city_fa,
        axis_name_fa,
        last_status_fa,
        max_amount,
        progress_project,
        operation_type_fa1,
        operation_type_fa2,
        operation_type_fa3,
        operation_type_fa4
        FROM
        (SELECT *,
        GREATEST(MAX(IFNULL(operation_type_amount1,0)), MAX(IFNULL(operation_type_amount2,0)), MAX(IFNULL(operation_type_amount3,0)), MAX(IFNULL(operation_type_amount4,0))) AS max_amount
        FROM contract_subitems
        WHERE province_id = {$request->province}
        AND project_type_id = 1
        GROUP BY unique_code) AS temp_table"
        ;

        $importantMaintananceProjectsExecute = DB::select($importantMaintananceProjects);


        /// important danger points projects
        $importantDangerPointsProject = "SELECT 
        city_fa,
        axis_name_fa,
        last_status_fa,
        '-' AS max_amount,
        progress_project,
        operation_type_fa1,
        operation_type_fa2,
        operation_type_fa3,
        operation_type_fa4
        FROM contract_subitems
        WHERE province_id = {$request->province}
        AND project_type_id = 2"
        ;

        $importantDangerPointsProjectExecute = DB::select($importantDangerPointsProject);

        /// important road upgrade safeties projects
        $importantRoadUpgradeSafetiesProject = "SELECT 
        city_fa,
        unique_code,
        axis_name_fa,
        last_status_fa,
        max_amount,
        progress_project,
        operation_type_fa1,
        operation_type_fa2,
        operation_type_fa3,
        operation_type_fa4
        FROM
        (SELECT *,
        GREATEST(MAX(IFNULL(operation_type_amount1,0)), MAX(IFNULL(operation_type_amount2,0)), MAX(IFNULL(operation_type_amount3,0)), MAX(IFNULL(operation_type_amount4,0))) AS max_amount
        FROM contract_subitems
        WHERE province_id = {$request->province}
        AND project_type_id = 3
        GROUP BY unique_code) AS temp_table"
        ;

        $importantRoadUpgradeSafetiesProjectExecute = DB::select($importantRoadUpgradeSafetiesProject);

        /// important techincal projects
        $importantTechnicalProject = "SELECT 
        city_fa,
        axis_name_fa,
        last_status_fa,
        '-' AS max_amount,
        progress_project,
        operation_type_fa1,
        operation_type_fa2,
        operation_type_fa3,
        operation_type_fa4
        FROM contract_subitems
        WHERE province_id = {$request->province}
        AND project_type_id = 4"
        ;

        $importantTechnicalProjectExecute = DB::select($importantTechnicalProject);

        /// important Tollhouse projects
        $importantTollhouseProject = "SELECT 
        city_fa,
        axis_name_fa,
        last_status_fa,
        '-' AS max_amount,
        progress_project,
        operation_type_fa1,
        operation_type_fa2,
        operation_type_fa3,
        operation_type_fa4
        FROM contract_subitems
        WHERE province_id = {$request->province}
        AND project_type_id = 5"
        ;

        $importantTollhouseProjectExecute = DB::select($importantTollhouseProject);

        /// important VillageRoad projects
        $importantVillageRoadProject = "SELECT 
         city_fa,
         axis_name_fa,
         last_status_fa,
         max_amount,
         progress_project,
         operation_type_fa1,
         operation_type_fa2,
         operation_type_fa3,
         operation_type_fa4
         FROM
         (SELECT *,
         GREATEST(MAX(IFNULL(operation_type_amount1,0)), MAX(IFNULL(operation_type_amount2,0)), MAX(IFNULL(operation_type_amount3,0)), MAX(IFNULL(operation_type_amount4,0))) AS max_amount
         FROM contract_subitems
         WHERE province_id = {$request->province}
         AND project_type_id = 6
         GROUP BY unique_code) AS temp_table"
        ;

        $importantVillageRoadProjectExecute = DB::select($importantVillageRoadProject);



        $data = [
            'summaryProjectsAllExecute' => $summaryProjectsAllExecute,
            'summaryProjectsStatusExecute' => $summaryProjectsStatusExecute,
            'summaryProjectsStatusByLastStatusExecute' => $summaryProjectsStatusByLastStatusExecute,
            'projectsStatusByCitiesExecute' => $projectsStatusByCitiesExecute,
            'importantMaintananceProjectsExecute' => $importantMaintananceProjectsExecute,
            'importantDangerPointsProjectExecute' => $importantDangerPointsProjectExecute,
            'importantRoadUpgradeSafetiesProjectExecute' => $importantRoadUpgradeSafetiesProjectExecute,
            'importantTechnicalProjectExecute' => $importantTechnicalProjectExecute,
            'importantTollhouseProjectExecute' => $importantTollhouseProjectExecute,
            'importantVillageRoadProjectExecute' => $importantVillageRoadProjectExecute,
            'province' => $getProvinceName,
            'province_id' => $request->province
        ];
        // dd($data);
        return view('word.template', $data);

        return abort(404);
    }

    public function show(Request $request, $id)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1004);
        }
        $subitem = ContractSubItems::where('contract_id', $id)->get();

        $data = [];

        foreach ($subitem as $key => $value) {
            /// [START] project_edit_data_index
            if (Auth::user()->can('edit-project')) {
                $canEdit = 1;
            } elseif (Auth::user()->can('edit-project-province') && (Auth::user()->province_id == $value->province_id)) {
                $canEdit = 1;
            } else {
                $canEdit = 0;
            }
            /// [END] project_edit_data_index


            /// [START] project_delete_data_index
            if (Auth::user()->can('delete-project')) {
                $canDelete = 1;
            } elseif (Auth::user()->can('delete-project-province') && (Auth::user()->province_id == $value->province_id)) {
                $canDelete = 1;
            } else {
                $canDelete = 0;
            }
            // dd($value->toArray());
            /// [END] project_edit_data_index
            $data[] = array(
                'axis_name_fa' => $value->axis_name_fa,
                'axis_type_fa' => $value->axis_type_fa,
                'axis_type_id' => $value->axis_type_id,
                'city_fa' => $value->city_fa,
                'city_id' => $value->city_id,
                'complete_payable' => $value->complete_payable,
                'contract_date_from_parent_contract' => $value->contract_date_from_parent_contract,
                'contract_id' => $value->contract_id,
                'contract_moshaver_nezarat' => $value->contract_moshaver_nezarat,
                'contract_moshaver_tarahi' => $value->contract_moshaver_tarahi,
                'created_at' => $value->created_at,
                'created_at_fa' => $value->created_at_fa,
                'end_lat' => $value->end_lat,
                'end_lng' => $value->end_lng,
                'end_way_id' => $value->end_way_id,
                'followup_priority_project' => $value->followup_priority_project,
                'followup_priority_project_id' => $value->followup_priority_project_id,
                'id' => $value->id,
                'image_path1' => $value->image_path1,
                'image_path2' => $value->image_path2,
                'last_date_update' => $value->last_date_update,
                'last_digit_project' => $value->last_digit_project,
                'last_function_operator' => $value->last_function_operator,
                'last_payable_operator' => $value->last_payable_operator,
                'last_status_fa' => $value->last_status_fa,
                'last_status_fa_for_chart' => $value->last_status_fa_for_chart,
                'last_status_id' => $value->last_status_id,
                'operation_type_amount1' => $value->operation_type_amount1,
                'operation_type_amount2' => $value->operation_type_amount2,
                'operation_type_amount3' => $value->operation_type_amount3,
                'operation_type_amount4' => $value->operation_type_amount4,
                'operation_type_fa1' => $value->operation_type_fa1,
                'operation_type_fa2' => $value->operation_type_fa2,
                'operation_type_fa3' => $value->operation_type_fa3,
                'operation_type_fa4' => $value->operation_type_fa4,
                'operation_type_id1' => $value->operation_type_id1,
                'operation_type_id2' => $value->operation_type_id2,
                'operation_type_id3' => $value->operation_type_id3,
                'operation_type_id4' => $value->operation_type_id4,
                'operation_type_progress1' => $value->operation_type_progress1,
                'operation_type_progress2' => $value->operation_type_progress2,
                'operation_type_progress3' => $value->operation_type_progress3,
                'operation_type_progress4' => $value->operation_type_progress4,
                'operation_type_tonaj1' => $value->operation_type_tonaj1,
                'operation_type_tonaj2' => $value->operation_type_tonaj2,
                'operation_type_tonaj3' => $value->operation_type_tonaj3,
                'operation_type_tonaj4' => $value->operation_type_tonaj4,
                'operation_type_unit1' => $value->operation_type_unit1,
                'operation_type_unit2' => $value->operation_type_unit2,
                'operation_type_unit3' => $value->operation_type_unit3,
                'operation_type_unit4' => $value->operation_type_unit4,
                'contract_number' => $value->contract_number,
                'operator_name' => $value->operator_name,
                'operator_phone' => $value->operator_phone,
                'priority_project' => $value->priority_project,
                'priority_project_fa' => $value->priority_project_fa,
                'progress_project' => $value->progress_project,
                'project_title' => $value->project_title,
                'project_type_fa' => $value->project_type_fa,
                'project_type_fa_for_chart' => $value->project_type_fa_for_chart,
                'project_type_id' => $value->project_type_id,
                'province_fa' => $value->province_fa,
                'province_id' => $value->province_id,
                'start_lat' => $value->start_lat,
                'start_lng' => $value->start_lng,
                'start_way_id' => $value->start_way_id,
                'unique_code' => $value->unique_code,
                'required_bitumen' => $value->required_bitumen,
                'used_bitumen' => $value->used_bitumen,
                'bridge_number' => $value->bridge_number,
                // 'updated_at' => Carbon::parse($value->updated_at)->setTimezone('Asia/Tehran')->,
                'updated_at' => $value->updated_at,
                'updated_at_fa' => $value->updated_at_fa,
                'user_id' => $value->user_id,
                'canEdit' => $canEdit,
                'canDelete' => $canDelete,
            );
            // dd($value->updated_at);
        }
        return response()->json([
            'message' => 'success',
            'data' => $data
        ]);
    }
}
