<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AppRequest;
use App\Models\User;
use App\Models\Worker;
use App\Models\WorkReq;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Morilog\Jalali\Jalalian;

class UserController extends Controller
{
    public function show()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $step = request()->input('step');
        $reqId = request()->input('reqId');
        $farmer_first_name = request()->input('farmer_first_name');
        $farmer_last_name = request()->input('farmer_last_name');
        $phone = request()->input('phone');
        $farm_name = request()->input('farm_name');
        $melli_code = request()->input('melli_code');
        $from = request()->input('from');
        $to = request()->input('to');
        $dateInterval = request()->input('dateInterval');

        $query = AppRequest::join('users', 'requests.user_id', '=', 'users.id')
            ->join('farmer_profiles', 'requests.user_id', '=', 'farmer_profiles.user_id')
            ->select('requests.*', 'users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name');

        if (isset($step)) {
            if ($step > 0) {
                $query->where('requests.step', $step);
            }

            if ($step == -1) {
                $query->where('requests.step', '<', 0);
                $query->where('requests.step', '>', -100);
            }

            if ($step == -100) {
                $query->where('requests.step', '<', -100);
            }
        }

        if (isset($reqId)) {
            $query->where('requests.id', $reqId);
        }

        if (isset($farmer_first_name)) {
            $query->where('users.first_name', $farmer_first_name);
        }

        if (isset($farmer_last_name)) {
            $query->where('users.last_name', $farmer_last_name);
        }

        if (isset($phone)) {
            $query->where('users.phone', $phone);
        }

        if (isset($farm_name)) {
            $query->where('farmer_profiles.farm_name', $farm_name);
        }

        if (isset($melli_code)) {
            $query->where('users.melli_code', $melli_code);
        }

        if (isset($from)) {
            $jDatefrom = Jalalian::fromFormat('Y/m/d H:i:s', $from)->toCarbon();
            //dd($jDatefrom->format('Y-m-d H:i:s'));
            //exit();
            $query->where('requests.created_at', '>=', $jDatefrom);
        }

        if (isset($to)) {
            $jDateto = Jalalian::fromFormat('Y/m/d H:i:s', $to)->toCarbon();
            $query->where('requests.created_at', '<=', $jDateto);
        }

        if (isset($dateInterval) && $dateInterval > 0) {
            $selectedDate = null;
            $today = Jalalian::now();
            switch ($dateInterval) {
                case 1:
                    $selectedDate = $today->subDays(7)->toCarbon();
                    break;
                case 2:
                    $selectedDate = $today->subMonths(1)->toCarbon();
                    break;
                case 3:
                    $selectedDate = $today->subMonths(3)->toCarbon();
                    break;
                case 4:
                    $selectedDate = $today->subMonths(6)->toCarbon();
                    break;
                case 5:
                    $selectedDate = $today->subMonths(12)->toCarbon();
                    break;
                case 6:
                    $selectedDate = $today->subDays(1)->toCarbon();
                    break;
            }

            if ($selectedDate !== null) {
                $query->where('requests.created_at', '>=', $selectedDate);
            }
        }

        $AllRequests = $query->get();

        if ($AllRequests != null) {
            $RequestCount = $AllRequests->count();

            $weightInfo = [
                "قرارداد" => 0,
                "گل" => 0,
                "کلاله تر" => 0,
                "زعفران" => 0,
                "حمل" => 0,
                "تعداد کل" => $RequestCount
            ];

            foreach ($AllRequests as $Req) {
                $weightarr = $Req->weight;
                //list($weight, $unit) = explode(' ', $weightarr['farmer']);
                $weightInfo1 = explode(' ', $weightarr['farmer']);


                if (count($weightInfo1) == 1) {
                    $weight = 0;
                    $unit = $weightInfo1[0];
                } else {
                    $weight = (int) $weightInfo1[0];
                    $unit = $weightInfo1[1];
                }



                if ($unit == 'گرم') {
                    $weight = $weight / 1000;
                }

                if (is_array($Req->transportation) && isset($Req->transportation['pricetotal'])) {
                    $weightInfo['حمل'] = $weightInfo['حمل'] + $Req->transportation['pricetotal'];
                }

                $weightInfo['گل'] = $weightInfo['گل'] + $weight;

                $contract = $Req->contract;
                if (isset($contract['pricetotal'])) {
                    $weightInfo['قرارداد'] = $weightInfo['قرارداد'] + $Req->contract['pricetotal'];
                }

                if (isset($weightarr['dryer']) && isset($weightarr['dryer']['زعفران'])) {
                    $weightInfo['کلاله تر'] = $weightInfo['کلاله تر'] + $weightarr['dryer']['کلاله'];
                    $weightInfo['زعفران'] = $weightInfo['زعفران'] + $weightarr['dryer']['زعفران'];
                }
            }
        }

        $RequestInfo = $query->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('Admin.index', compact(['RequestInfo', 'weightInfo']));
    }

    public function view($id = null)
    {
        if ($id != null && $id > 0) {
            $RequestInfo = AppRequest::where('requests.id', $id)
                ->join('users', 'requests.user_id', '=', 'users.id')
                ->join('farmer_profiles', 'requests.user_id', '=', 'farmer_profiles.user_id')
                ->select('requests.*', 'users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name')
                ->first();

            $weightInfo = $RequestInfo->weight;

            if (isset($weightInfo['chief'])) {
                foreach ($weightInfo['chief'] as $key => $weightcw) {
                    $UserInfo = User::find($key);
                    $weightcw['name'] = $UserInfo->first_name . ' ' . $UserInfo->last_name;
                    $weightInfo['chief'][$key] = $weightcw;
                }
            }

            $UserRequests = WorkReq::where('user_requests.request_id', $id)
                ->join('users', 'users.id', 'user_requests.user_id')
                ->select('user_requests.info', 'users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'users.role', 'users.id')
                ->get();

            $userSubs = WorkReq::where('user_requests.request_id', $id)
                ->join('users', 'users.id', 'user_requests.user_id')
                ->join('user_profiles', 'users.id', 'user_profiles.user_id')
                ->where('users.role', 'chief_worker')
                ->select('users.first_name', 'users.last_name', 'user_profiles.sub_users', 'users.id')
                ->get();

            foreach ($userSubs as &$userSub) {
                if ($userSub->sub_users != null) {
                    $subUserIds = json_decode($userSub->sub_users, true);
                    $newsub = [];

                    foreach ($subUserIds as $usid) {
                        $UserInfo = User::find($usid);
                        if ($UserInfo) {
                            $newsub[] = $UserInfo->first_name . ' ' . $UserInfo->last_name;
                        }
                    }

                    $userSub->sub_users = $newsub;
                }
            }
            unset($userSub);



            return view('Admin.view', compact(['RequestInfo', 'userSubs', 'UserRequests', 'weightInfo']));
        }

        return redirect()->route('admin.panel');
    }

    public function works()
    {

        $perPage = 25;
        $page = request()->input('page', 1);
        $step = request()->input('step');
        $userId = request()->input('userId');
        $first_name = request()->input('first_name');
        $last_name = request()->input('last_name');
        $phone = request()->input('phone');
        $role = request()->input('role');
        $melli_code = request()->input('melli_code');
        $from = request()->input('from');
        $to = request()->input('to');
        $dateInterval = request()->input('dateInterval');



        $query = User::where("users.role", '!=', 'farmer')->select('users.*');



        if (isset($userId)) {
            $query->where('users.id', $userId);
        }

        if (isset($first_name)) {
            $query->where('users.first_name', $first_name);
        }

        if (isset($last_name)) {
            $query->where('users.last_name', $last_name);
        }

        if (isset($phone)) {
            $query->where('users.phone', $phone);
        }

        if (isset($role) && $role != 0) {
            $query->where('users.role', $role);
        }

        if (isset($melli_code)) {
            $query->where('users.melli_code', $melli_code);
        }



        $AllselectedUsers = $query->get();

        $all_user_id = [];
        $price_data = [];
        $weight_data = [];
        if ($AllselectedUsers !== null) {
            foreach ($AllselectedUsers as $susid) {
                $all_user_id[] = $susid->id;

                $price_data[$susid->id] = 0;
                $weight_data[$susid->id] = 0;
            }
        }



        $RequestQuery = AppRequest::where(function ($Appquery) use ($all_user_id) {
            foreach ($all_user_id as $userId) {
                $Appquery->orWhereJsonContains('step_info', ['user_id' => (int)$userId]);
                $Appquery->orWhereJsonContains('transportation', ['user_id' => (string)$userId]);
            }
        });



        if (isset($step)) {
            if ($step > 0) {
                $RequestQuery->where('requests.step', $step);
            }

            if ($step == -1) {
                $RequestQuery->where('requests.step', '<', 0);
                $RequestQuery->where('requests.step', '>', -100);
            }

            if ($step == -100) {
                $RequestQuery->where('requests.step', '<', -100);
            }
        }

        if (isset($from)) {
            $jDatefrom = Jalalian::fromFormat('Y/m/d', $from)->toCarbon();
            $RequestQuery->where('requests.created_at', '>=', $from);
        }

        if (isset($to)) {
            $jDateto = Jalalian::fromFormat('Y/m/d', $to)->toCarbon();
            $RequestQuery->where('requests.created_at', '<=', $to);
        }

        if (isset($dateInterval) && $dateInterval > 0) {
            $selectedDate = null;
            $today = Jalalian::now();
            switch ($dateInterval) {
                case 1:
                    $selectedDate = $today->subDays(7)->toCarbon();
                    break;
                case 2:
                    $selectedDate = $today->subMonths(1)->toCarbon();
                    break;
                case 3:
                    $selectedDate = $today->subMonths(3)->toCarbon();
                    break;
                case 4:
                    $selectedDate = $today->subMonths(6)->toCarbon();
                    break;
                case 5:
                    $selectedDate = $today->subMonths(12)->toCarbon();
                    break;
            }

            if ($selectedDate !== null) {
                $RequestQuery->where('requests.created_at', '>=', $selectedDate);
            }
        }

        $AllRequests = $RequestQuery->get();



        if ($AllRequests && $AllRequests->isNotEmpty()) {
            $RequestCount = $AllRequests->count();

            $weightInfo = [
                "قرارداد" => 0,
                "گل" => 0,
                "کلاله تر" => 0,
                "زعفران" => 0,
                "حمل" => 0,
                "تعداد کل" => $RequestCount
            ];

            // گرفتن تمام id ها برای کاهش query
            $requestIds = $AllRequests->pluck('id')->toArray();
            $userIds = $AllselectedUsers->pluck('id')->toArray();

            // گرفتن تمام WorkReq های مربوط به این request ها و user ها یکجا
            $workreqs = WorkReq::whereIn('request_id', $requestIds)
                ->whereIn('user_id', $userIds)
                ->get()
                ->groupBy(function ($item) {
                    return $item->request_id . '_' . $item->user_id;
                });

            foreach ($AllRequests as $Req) {
                $weightarr = $Req->weight ?? [];

                $farmerWeight = $weightarr['farmer'] ?? "0 کیلوگرم";
                $weightInfo1 = explode(' ', $farmerWeight);

                $weight = (float)($weightInfo1[0] ?? 0);
                $unit = $weightInfo1[1] ?? 'کیلوگرم';

                if ($unit === 'گرم') {
                    $weight /= 1000;
                }

                $weightInfo['گل'] += $weight;

                if (!empty($Req->contract['pricetotal'])) {
                    $weightInfo['قرارداد'] += (float)$Req->contract['pricetotal'];
                }

                if (!empty($Req->transportation['pricetotal'])) {
                    $weightInfo['حمل'] += (float)$Req->transportation['pricetotal'];
                }

                if (!empty($weightarr['dryer']['کلاله'])) {
                    $weightInfo['کلاله تر'] += (float)$weightarr['dryer']['کلاله'];
                }

                if (!empty($weightarr['dryer']['زعفران'])) {
                    $weightInfo['زعفران'] += (float)$weightarr['dryer']['زعفران'];
                }

                foreach ($AllselectedUsers as $susid) {
                    $key = $Req->id . '_' . $susid->id;
                    $workreq_temp = $workreqs->get($key)?->first();

                    if (!$workreq_temp) continue;

                    $info = $workreq_temp->info ?? [];

                    switch ($susid->role) {
                        case 'transporter':
                            if (
                                !empty($Req->transportation['pricetotal']) &&
                                ($Req->transportation['user_id'] ?? null) == $susid->id
                            ) {
                                $price_data[$susid->id] = ($price_data[$susid->id] ?? 0) + $Req->transportation['pricetotal'];
                            }
                            break;

                        case 'worker':
                            if (!empty($info['workerprice']) && !empty($info['weight'])) {
                                $price_data[$susid->id] = ($price_data[$susid->id] ?? 0) + ((int) $info['workerprice'] * (float) $info['weight']);
                            }
                            if (!empty($info['weight'])) {
                                $weight_data[$susid->id] = ($weight_data[$susid->id] ?? 0) + (float)$info['weight'];
                            }
                            break;

                        case 'chief_worker':
                            if (!empty($info['chiefprice']) && !empty($info['weight'])) {
                                $price_data[$susid->id] = ($price_data[$susid->id] ?? 0) + ((int) $info['chiefprice'] * (float) $info['weight']);
                            }
                            if (!empty($info['weight'])) {
                                $weight_data[$susid->id] = ($weight_data[$susid->id] ?? 0) + (float)$info['weight'];
                            }
                            break;
                    }
                }
            }
        }

        $RequestQuery = $RequestQuery->join('users', 'requests.user_id', '=', 'users.id')
            ->join('farmer_profiles', 'requests.user_id', '=', 'farmer_profiles.user_id')
            ->select('requests.*', 'users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name');


        $RequestInfo = $RequestQuery->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('Admin.worker', compact(['RequestInfo', 'AllselectedUsers', 'weightInfo', 'price_data', 'weight_data']));
    }

    public function cancel(Request $request)
    {
        if ($request->input('CancelId') !== null && ctype_digit($request->input('CancelId')) && (int) $request->input('CancelId') > 0) {
            $RequestInfo = AppRequest::find($request->input('CancelId'));
            $oldStep =  $RequestInfo->step;

            if ($oldStep > 0) {
                $oldStep *= -1;
            }
            $RequestInfo->step =  $oldStep - 100;
            $stepInfo = $RequestInfo->step_info;

            if (!is_array($stepInfo)) {
                $stepInfo = [];
            }



            $stepInfo[] = [
                'action' => 'لغو شد',
                'user_id' => Auth::id(),
                'date' => Jalalian::now()->format('Y/m/d H:i:s')
            ];
            $RequestInfo->step_info =  $stepInfo;
            $RequestInfo->save();
            return redirect()->route('admin.panel')->with('success', 'سفارش با موفقیت لغو شد.');
        }

        return redirect()->back()->with('error', 'سفارش معتبری برای لغو پیدا نشد.');
    }

    public function delete(Request $request)
    {
        if ($request->input('deleteId') !== null && ctype_digit($request->input('deleteId')) && (int) $request->input('deleteId') > 0) {
            $deleteId = $request->input('deleteId');
            $requestInfo = AppRequest::find($deleteId);

            if ($requestInfo) {
                WorkReq::where('request_id', $deleteId)->delete();
                $requestInfo->delete();

                return redirect()->route('admin.panel')->with('success', 'سفارش با موفقیت حذف شد.');
            }
            return redirect()->route('admin.panel')->with('error', 'سفارش معتبری برای حذف پیدا نشد.');
        }

        return redirect()->back()->with('error', 'سفارش معتبری برای حذف پیدا نشد.');
    }

    public function stepchange(Request $request)
    {
        $reqId = $request->input('requestId');
        $step = $request->input('step');

        if (ctype_digit($step) && $step > 0 && ctype_digit($reqId) && $reqId > 0) {
            $requestInfo = AppRequest::find($reqId);
            $requestInfo->step = $step;
            $requestInfo->save();

            return redirect()->back()->with('success', 'وضعیت تغییر یافت');
        }

        return redirect()->back()->with('error', 'درخواست معتبر نمی باشد.');
    }

    public function remove(Request $request)
    {
        $reqId = $request->input('requestId');
        $userId = $request->input('userId');

        if (ctype_digit($userId) && $userId > 0 && ctype_digit($reqId) && $reqId > 0) {
            $userRequest = WorkReq::where('request_id', $reqId)
                ->where('user_id', $userId)
                ->first();
            $userRequest->delete();

            $userInfo = Worker::where('user_id', $userId)->first();

            if ($userInfo->sub_users != null) {
                foreach ($userInfo->sub_users as $usersub) {
                    $userRequest = WorkReq::where('request_id', $reqId)
                        ->where('user_id', $usersub)
                        ->first();
                    if ($userRequest != null) {
                        $userRequest->delete();
                    }
                }
            }

            return redirect()->back()->with('success', 'تخصیص کار حذف شد');
        }

        return redirect()->back()->with('error', 'درخواست معتبر نمی باشد.');
    }

    public function printlist()
    {
        $step = request()->input('step');
        $reqId = request()->input('reqId');
        $farmer_first_name = request()->input('farmer_first_name');
        $farmer_last_name = request()->input('farmer_last_name');
        $phone = request()->input('phone');
        $farm_name = request()->input('farm_name');
        $melli_code = request()->input('melli_code');
        $from = request()->input('from');
        $to = request()->input('to');
        $dateInterval = request()->input('dateInterval');

        $query = AppRequest::join('users', 'requests.user_id', '=', 'users.id')
            ->join('farmer_profiles', 'requests.user_id', '=', 'farmer_profiles.user_id')
            ->select('requests.*', 'users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name');

        if (isset($step)) {
            if ($step > 0) {
                $query->where('requests.step', $step);
            }

            if ($step == -1) {
                $query->where('requests.step', '<', 0);
                $query->where('requests.step', '>', -100);
            }

            if ($step == -100) {
                $query->where('requests.step', '<', -100);
            }
        }

        if (isset($reqId)) {
            $query->where('requests.id', $reqId);
        }

        if (isset($farmer_first_name)) {
            $query->where('users.first_name', $farmer_first_name);
        }

        if (isset($farmer_last_name)) {
            $query->where('users.last_name', $farmer_last_name);
        }

        if (isset($phone)) {
            $query->where('users.phone', $phone);
        }

        if (isset($farm_name)) {
            $query->where('farmer_profiles.farm_name', $farm_name);
        }

        if (isset($melli_code)) {
            $query->where('users.melli_code', $melli_code);
        }

        if (isset($from)) {
            $jDatefrom = Jalalian::fromFormat('Y/m/d H:i:s', $from)->toCarbon();
            $query->where('requests.created_at', '>=', $jDatefrom);
        }

        if (isset($to)) {
            $jDateto = Jalalian::fromFormat('Y/m/d H:i:s', $to)->toCarbon();
            $query->where('requests.created_at', '<=', $jDateto);
        }

        if (isset($dateInterval) && $dateInterval > 0) {
            $selectedDate = null;
            $today = Jalalian::now();
            switch ($dateInterval) {
                case 1:
                    $selectedDate = $today->subDays(7)->toCarbon();
                    break;
                case 2:
                    $selectedDate = $today->subMonths(1)->toCarbon();
                    break;
                case 3:
                    $selectedDate = $today->subMonths(3)->toCarbon();
                    break;
                case 4:
                    $selectedDate = $today->subMonths(6)->toCarbon();
                    break;
                case 5:
                    $selectedDate = $today->subMonths(12)->toCarbon();
                    break;
                case 6:
                    $selectedDate = $today->subDays(1)->toCarbon();
                    break;
            }

            if ($selectedDate !== null) {
                $query->where('requests.created_at', '>=', $selectedDate);
            }
        }

        $AllRequests = $query->get();

        $filename = "requests_" . date('Y-m-d_H-i-s') . ".csv";

        header("Content-Type: text/csv; charset=utf-8");
        header("Content-Disposition: attachment; filename=$filename");

        $output = fopen('php://output', 'w');

        fputcsv($output, [
            'کد سفارش',
            'نام',
            'نام خانوادگی',
            'شماره تماس',
            'نام مزرعه',
            'کد ملی',
            'وزن گل',
            'وضعیت',
            'تاریخ ثبت'
        ]);

        foreach ($AllRequests as $req) {

            $stepName = $req->step;

            switch ($stepName) {
                case 1:
                    $stepName = "درخواست جدید";
                    break;
                case 2:
                    $stepName = "در انتظار تایید کشاورز";
                    break;
                case 3:
                    $stepName = "قرارداد تایید شد";
                    break;
                case 4:
                    $stepName = " در انتظار تحویل";
                    break;
                case 5:
                    $stepName = "در انتظار تایید مرکز فراوری";
                    break;
                case 6:
                    $stepName = "دریافت توسط مرکز فراوری";
                    break;
                case 7:
                    $stepName = "توزیع به سرتیم ها";
                    break;
                case 8:
                    $stepName = "اعلام اتمام کار توسط کارگران";
                    break;
                case 9:
                    $stepName = "اتمام کار توسط همه سرتیم ها";
                    break;
                case 10:
                    $stepName = "دریافت توسط مرکز خشک کن";
                    break;
                case 11:
                    $stepName = "اتمام خشک کردن";
                    break;
                case 12:
                    $stepName = "دریافت توسط واحد بسته بندی";
                    break;
                case 13:
                    $stepName = "اتمام سفارش و ارسال";
                    break;
            }

            fputcsv($output, [
                $req->id,
                $req->first_name,
                $req->last_name,
                $req->phone,
                $req->farm_name,
                $req->melli_code,
                $req->weight['farmer'],
                $stepName,
                jdate($req->created_at)->format('Y/m/d')
            ]);
        }

        fclose($output);
        exit;
    }

    public function printfarmer()
    {
        $query = User::where('users.role', 'farmer')
            ->whereExists(function ($query) {
                $query->select(AppRequest::raw(1))
                    ->from('requests')
                    ->whereRaw('requests.user_id = users.id');
            })
            ->join('requests', 'requests.user_id', 'users.id')
            ->join('farmer_profiles', 'farmer_profiles.user_id', 'users.id')
            ->select('users.first_name', 'users.last_name', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name')
            ->distinct();

        $AllUsers = $query->get();

        $filename = "requests_" . date('Y-m-d_H-i-s') . ".csv";

        header("Content-Type: text/csv; charset=utf-8");
        header("Content-Disposition: attachment; filename=$filename");

        $output = fopen('php://output', 'w');

        fputcsv($output, [
            'نام',
            'نام خانوادگی',
            'شماره تماس',
            'کد ملی',
            'نام مزرعه',
            'استان',
            'شهر',
            'آدرس'
        ]);

        foreach ($AllUsers as $user) {
            fputcsv($output, [
                $user->first_name,
                $user->last_name,
                $user->phone,
                $user->melli_code,
                $user->farm_name,
                $user->state,
                $user->city,
                $user->address
            ]);
        }

        fclose($output);
        exit;
    }

    public function sendnotif()
    {
        return view('Admin.sendnotif');
    }
}
