<?php

namespace App\Http\Controllers\Dryer;

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

class UserController extends Controller
{
    public function show()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $farmer_first_name = request()->input('fname');
        $farmer_last_name = request()->input('lname');
        $from = request()->input('from');
        $to = request()->input('to');
        
        $query = AppRequest::where('requests.step', 9)
            ->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($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($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);
        }


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

        return view('dryer.index', compact('RequestInfo'));
    }

    public function viewEdit($id = null)
    {
        if ($id != null && (int) $id > 0) {
            $Settings = Settings::where('title','dryer_salary')->first();
            $dryer_salary = $Settings->value;

            $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();
            
            $Chief_Workers = WorkReq::where('user_requests.request_id',$id)
                            ->join('users', 'user_requests.user_id', '=', 'users.id')
                            ->where('users.role','chief_worker')
                            ->select('users.id','users.first_name','users.last_name')
                            ->get();

            return view('dryer.edit', compact(['RequestInfo','Chief_Workers','dryer_salary']));
        }

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

    public function accept(Request $request)
    {
        $colale = $request->colale;
        $reqid = $request->requestId;
        $RequestInfo = AppRequest::where('id', $reqid)->first();

        WorkReq::where('user_requests.request_id', $reqid)
                    ->join('users', 'users.id', 'user_requests.user_id')
                    ->where('users.role', 'chief_worker')
                    ->update([
                        'info->vaziat' => 100
                    ]);

        $RequestInfo->step = 10;

        

        $stepInfo = $RequestInfo->step_info;

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

        $stepInfo[] = [
            'action' => 'واحد خشک کن ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' کلاله را تحویل گرفت.',
            'user_id' => Auth::id(),
            'date' => Jalalian::now()->format('Y/m/d H:i:s')
        ];

        $RequestInfo->step_info =  $stepInfo;

        $oldweight = $RequestInfo->weight;

        $oldweight['dryer'] = [
                    'کلاله' => $colale
                ]; 
        $RequestInfo->weight = $oldweight;

        $RequestInfo->save();

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

    public function current()
    {
        
        $Settings = Settings::where('title','dryer_salary')->first();
        $dryer_salary = $Settings->value;

        $perPage = 25;
        $page = request()->input('page', 1);
        $query = AppRequest::where('requests.step', 10)
            ->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 = $query->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('dryer.index', compact(['RequestInfo','dryer_salary']));
    }

    public function currentAccept(Request $request)
    {
        $safrane = $request->safrane;
        $priceunit = $request->priceunit;
        $reqid = $request->requestId;
        $RequestInfo = AppRequest::where('id', $reqid)->first();

        $RequestInfo->step = 11;

        $stepInfo = $RequestInfo->step_info;

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

        $stepInfo[] = [
            'action' => 'واحد خشک کن ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' کار را تمام کرد.',
            'user_id' => Auth::id(),
            'date' => Jalalian::now()->format('Y/m/d H:i:s')
        ];

        $RequestInfo->step_info =  $stepInfo;

        $oldweight = $RequestInfo->weight;

        $oldweight['dryer']['زعفران'] = $safrane; 

        $RequestInfo->weight = $oldweight;

        $contract = $RequestInfo->contract;

        if(!is_array($contract))
        {
            $contract = json_decode($contract, true);
        }

        $dryerprice = (int) $priceunit * ((int) $oldweight['dryer']['کلاله']);

        $contract['dryerprice'] = $dryerprice;
        $contract['dryerpriceunit'] = $priceunit;

        $RequestInfo->contract = $contract;

        $RequestInfo->save();

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

    public function oldlist()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $query = AppRequest::where('requests.step', '>' , 10)
            ->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 = $query->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('dryer.index', compact('RequestInfo'));
    }

    public function disagree(Request $request)
    {
        $RequestInfo = AppRequest::where('id', $request->reqId)->first();

        $stepInfo = $RequestInfo->step_info;

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

        $stepInfo[] = [
            'action' => 'اعلام مغایرت توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' توضیح: ' . $request->reason,
            'user_id' => Auth::id(),
            'date' => Jalalian::now()->format('Y/m/d H:i:s')
        ];

        $RequestInfo->step_info =  $stepInfo;

        $oldstep =  $RequestInfo->step;

        if ((int) $oldstep > 0) {
            $RequestInfo->step = $oldstep * -1;
        }
        $RequestInfo->save();

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

    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;
    }
}
