<?php

namespace App\Http\Controllers\Workplace;

use App\Http\Controllers\Controller;
use App\Models\OrganizationDepartment;
use App\Models\ProductCategory;
use App\Models\ProjectAttachments;
use App\Models\ProjectBudget;
use App\Models\Projects;
use App\Models\ProjectDepartment;
use App\Models\ProjectRequirement;
use App\Models\ProjectRequirements;
use App\Models\ProjectTeam;
use App\Models\ProjectType;
use App\Models\VoucherMaster;
use Illuminate\Http\Request;

class ProjectsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:projects-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Projects::select([
            'id',
            'title',
            'code',
            'product_category_id',
            'project_type_id',
            'department_id',
            'receive_date',
            'start_date',
            'dead_line_date',
            'about',
            'priority',
            'status'
            ])
            ->with('getProjectType')
            ->with('getDepartments')
            ->with('getProductCategory')
            ->orderBy('id', 'desc');
        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('business_name', 'like', '%'.$search_query.'%')
                                ->orWhere('phone_number', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);

            return view('projects.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('projects.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $department      = OrganizationDepartment::select('id','name')->where('status',1)->get();
        $productCategory = ProductCategory::select('id','name')->where('status',1)->get();
        $projectType     = ProjectType::select('id','title')->where('status',1)->get();
        $priority        = Projects::max('priority');
        $priority        = $priority != '' ? $priority : 0;

        return view('projects.create',compact('productCategory', 'department','projectType','priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'title'                 => 'required',
            'project_type_id'       => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'receive_date',
            'start_date',
            'dead_line_date',
            'department_id'
        ]);

        $data['receive_date'] = $request->receive_date != '' && $request->receive_date != '0000-00-00' &&  $request->receive_date != Null ? date('Y-m-d', strtotime($request->receive_date)) : null;
        $data['start_date'] = $request->start_date != '' && $request->start_date != '0000-00-00' &&  $request->start_date != Null ? date('Y-m-d', strtotime($request->start_date)) : null;
        $data['dead_line_date'] = $request->dead_line_date != '' && $request->dead_line_date != '0000-00-00' &&  $request->dead_line_date != Null ? date('Y-m-d', strtotime($request->dead_line_date)) : null;

        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'PROJECTS')->first();
        // echo "<pre>";
        // print_r($voucher_master);
        // echo "</pre>";
        // die();
        $voucher_count      = Projects::select('last_voucher_count')->orderBy('created_at', 'DESC')->first();

        $last_voucher_count = isset($voucher_count) && isset($voucher_count->last_voucher_count) ? $voucher_count->last_voucher_count + 1 : ($voucher_master->voucherSeries->start_from + 1 ?? 1);

        $main_invoice_no = $this->generateCode(
            $last_voucher_count,
            ($voucher_master->voucherSeries->prefix ?? 'PRO'),
            ($voucher_master->voucherSeries->postfix ?? ''),
            ($voucher_master->voucherSeries->separator ?? '-'),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        $data['code']               = $main_invoice_no;
        $data['last_voucher_count'] = $last_voucher_count;

        $project = Projects::create($data);

        if ($request->has('department_id') && !is_null($request->department_id))
            foreach ($request->department_id as $departmentId)
        {
            $projectDepartmentData =
            [
                'project_id'    => $project->id,
                'department_id' => $departmentId,
            ];

            ProjectDepartment::create($projectDepartmentData);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Project created successfully',
                'data'    => $project
            ]);
        }

        return redirect()->route('projects.index')->with('success','Project created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Projects::select([
            'id',
            'title',
            'code',
            'product_category_id',
            'project_type_id',
            'department_id',
            'receive_date',
            'start_date',
            'dead_line_date',
            'about',
            'priority',
            'status'
            ])
            ->with('getProjectType')
            ->with('getDepartments')
            ->with('getProductCategory')
            ->where('id', $id)
            ->first();

        $project            = ProjectBudget::where('projects_id', $id)->first();
        $ProjectAttachments = ProjectAttachments::where('projects_id', $id)->first();
        $projectRequirments = ProjectRequirement::where('project_id',$id)->first();
        $projectTeams       = ProjectTeam::where('project_id',$id)->first();

        return view('projects.show',compact('data','project','ProjectAttachments','projectRequirments','projectTeams'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $project         = Projects::find($id);

        // Get the associated department IDs for the current project
        $department_ids = ProjectDepartment::where('project_id', $id)->get()->pluck('department_id')->toArray();

        $department = OrganizationDepartment::select('id','name')->where('status',1)->get();
        $productCategory = ProductCategory::select('id','name')->where('status',1)->get();
        $projectType = ProjectType::select('id','title')->where('status',1)->get();

        return view('projects.edit',compact('productCategory', 'department_ids','projectType','department','productCategory','project'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'title'                 => 'required',
            'project_type_id'       => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'receive_date',
            'start_date',
            'dead_line_date',
            'department_id'
        ]);

        $data['receive_date']      = date('Y-m-d', strtotime($request->receive_date));
        $data['start_date']        = date('Y-m-d', strtotime($request->start_date));
        $data['dead_line_date']    = date('Y-m-d', strtotime($request->dead_line_date));

        $marketig = Projects::find($id);

        if (!$marketig) {
            return redirect()->route('marketing.index')
                ->with('error','Project not found!');
        }

        $marketig->update($data);

        ProjectDepartment::where('project_id' , $id)->whereNotIn('department_id' , $request->department_id )->delete();

        foreach ($request->department_id as $departmentId)
        {
            $projectDepartmentData =
            [
                'project_id' => $id,
                'department_id' => $departmentId,
            ];

            ProjectDepartment::updateOrCreate($projectDepartmentData);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Project updated successfully',
                'data'    => $marketig
            ]);
        }

        return redirect()->route('marketing.index')
            ->with('success','Project updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = Projects::find($request->id);

        Projects::find($request->id)->delete();

        $Redirect = 'classes';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = Projects::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Project status successfully change'],
                    'data' => [
                        'redirect' => '/classes/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }


    public function projectBudget(Request $request, $id)
    {
        $projectBudget = projectBudget::where('projects_id', $id)->get();

        return view('project-budgets.table', compact('projectBudget'));
    }
    public function projectProjectAttachment(Request $request, $id)
    {
        $ProjectAttachments = ProjectAttachments::where('projects_id', $id)->get();

        return view('project-attachments.table', compact('ProjectAttachments'));
    }

    public function projectRequirment(Request $request, $id)
    {
        $ProjectRequirment = ProjectRequirement::all();
        $data = Projects::select([
            'id',
            'features',
            'project_id',
            'task_type_id',
            'note'
            ])
            ->with('getProject')
            ->with('getProjectType');

        return view('project-requirements.table', compact('ProjectRequirment','data'));

    }

    public function projectTeam(Request $request, $id)
    {
        $projectTeam = ProjectTeam::where('project_id', $id)->get();
        $data = ProjectTeam::select([
            'team_user_id',
            'role_in_project',
            'is_manager',
            'assign_date',
            'release_date',
            'status'
        ])
            ->with('getUserId');
        return view('project-teams.table', compact('projectTeam','data'));
    }
}
