HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux ip-172-26-0-120 6.17.0-1009-aws #9~24.04.2-Ubuntu SMP Fri Mar 6 23:50:29 UTC 2026 x86_64
User: ubuntu (1000)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/owlcrm/app/Http/Controllers/ProjectController.php
<?php

namespace App\Http\Controllers;

use App\Models\Amenities;
use App\Models\City;
use App\Models\Company;
use App\Models\Country;
use App\Models\Project;
use App\Models\ProjectAmenity;
use App\Models\ProjectNotes;
use App\Models\Property;
use App\Models\States;
use App\Models\User;
use App\Models\UserProject;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

use function Laravel\Prompts\alert;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $search_keyword = '';
            $status = 'all'; // all status
            $request_data = $request->all();
            if ($request->has('search_keyword')) {
                $search_keyword = $request->search_keyword;
            }
            if ($request->has('status_filter')) {
                $status = $request->status_filter;
            }
            // avoid zero column as it's checkbox so we can't sort by it
            if ($request->has('order') && $request->order[0]['column'] != 0) {
                $sort_column_number = $request->order[0]['column'];
                $sort_column_dir = $request->order[0]['dir'];
                $sort_column_key = $request->columns[$sort_column_number]['data'];
            }

            $user = auth()->user();
            $main_query = Project::query()
            ->where(function ($query) {
                // Logged-in admin ka apna data
                $query->where('user_id', '=', auth()->id())
        
                    // Parent ka data
                    ->orWhere('user_id', '=', auth()->user()->parent_id);
        
                // Siblings ka data (same parent_id, excluding logged-in admin)
                if (!is_null(auth()->user()->parent_id)) {
                    $query->orWhereIn('user_id', function ($subQuery) {
                        $subQuery->select('id')
                            ->from('users')
                            ->where('parent_id', auth()->user()->parent_id) // Same parent_id wale
                            ->where('id', '!=', auth()->id()); // Exclude logged-in admin
                    });
                }
            });
        
        
            $query = $main_query;
            if (!empty($search_keyword)) {
                $query = $query->where('title', 'LIKE', '%' . $search_keyword . '%');
            }
            if ($status != 'all' && $status != '') {
                $query = $query->where('status', $status);
            }
            if (!empty($sort_column_key)) {
                $query = $query->orderBy($sort_column_key, $sort_column_dir);
            } else {
                $query = $query->latest();
            }

            $data = $query->with('its_company', 'its_country', 'its_states')->get();
            $count_total = $main_query->count();
            $count_filter = $count_total;
            return DataTables::of($data)

                ->addColumn('company_id', function ($row) {
                    return isset($row->its_company) ? $row->its_company->name : '';
                })
                ->addColumn('title', function ($row) {
                    return $row->title;
                })
                ->addColumn('description', function ($row) {
                    return $row->description;
                })
                ->addColumn('nature', function ($row) {
                    return $row->nature;
                })
                ->addColumn('start_date', function ($row) {
                    return formatDate($row->start_date, 'Y/m/d H:i:s');
                })
                ->addColumn('address', function ($row) {
                    // return $row->address_line_1 . ', ' . $row->address_line_2 . ',' . $row->its_city->name . ',' . $row->its_states->name . ',' . $row->its_country->name . ',' . $row->postal_code;
                    return $row->address_line_1 . ' ' . $row->address_line_2 . ' ' . isset($row->its_city) ?? $row->its_city->name . ' ' . isset($row->its_states) ?? $row->its_states->name . ' ' . isset($row->its_country) ?? $row->its_country->name . ' ' . $row->postal_code;
                })
                ->editColumn('status', function ($row) {
                    $update_url = route('user.update.project.status', $row->id);
                    return setStatus($row, $update_url);
                })
                ->addColumn('action', function ($row) {

                    if ($row->is_admin !== 1) {
                        return view('users.project.partially.delete', ['row' => $row])->render();
                    }
                })
                ->rawColumns(['action', 'status'])
                ->with([
                    "recordsTotal"    => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->make(true);
        }
        return view('users.project.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $currentUser = auth()->user();
    
        // Fetch companies related to the current user, their parent, and siblings
        $companies = Company::query()
            ->where(function ($query) use ($currentUser) {
                $query->where('created_by', $currentUser->id) // Companies created by the current user
                    ->orWhere('created_by', $currentUser->parent_id); // Companies created by the parent
    
                // Fetch companies related to siblings (users with the same parent_id as the current user)
                if (!is_null($currentUser->parent_id)) {
                    $query->orWhereIn('created_by', User::where('parent_id', $currentUser->parent_id)->pluck('id'));
                }
    
                // Optional: Add logic for grandparents (parent of the parent) if needed
                if (!is_null($currentUser->parent) && !is_null($currentUser->parent->parent_id)) {
                    $query->orWhereIn('created_by', User::where('parent_id', $currentUser->parent->parent_id)->pluck('id'));
                }
            })
            ->get();
    
        // Fetch countries (assuming these are global and not user-specific)
        $countries = Country::all();
    
        // Fetch users created by the current user, their parent, siblings, or children
        $users = User::query()
        ->where('status', User::ACTIVE) // Only active users
            ->where(function ($query) use ($currentUser) {
                $query->where('id', $currentUser->id) // Current user
                    ->orWhere('id', $currentUser->parent_id); // Parent user
    
                // Sibling users (users with the same parent_id as the current user)
                if (!is_null($currentUser->parent_id)) {
                    $query->orWhere('parent_id', $currentUser->parent_id);
                }
    
                // Child users (users where the current user is the parent)
                $query->orWhere('parent_id', $currentUser->id);
            })
            ->get();
    
        // Fetch amenities created by the current user or their parent
        $amenities = Amenities::query()
            ->where(function ($query) use ($currentUser) {
                $query->where('created_by', $currentUser->id) // Amenities created by current user
                    ->orWhere('created_by', $currentUser->parent_id); // Amenities created by parent
            })
            ->get();
    
        // Fetch other resources (if needed)
        $user_project = UserProject::all();
        $project_amenities = ProjectAmenity::all();
    
        // Return the view with the necessary data
        return view('users.project.create', compact('companies', 'countries', 'users', 'user_project', 'amenities', 'project_amenities'));
    }
    
    
    
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());

        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'company_id' => 'required|exists:companies,id',
            'nature' => 'required',
            'user_id' => 'required|exists:users,id',
            'notes' => 'nullable|string',
            'amenity_id' => 'required|exists:amenities,id',

        ]);


        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $project = new Project();

        $currentUserId = getAdminId();
        $project ->created_by = auth()->id();
  
        $project->user_id = isset(auth()->user()->parent_id) ? auth()->user()->parent_id : auth()->id() ; 
        if (isset($project)) {
            $project->company_id = $request->company_id;
            $project->title = $request->title;
            $project->description = $request->description;
            $project->nature = $request->nature;
            $project->start_date = $request->start_date;
            $project->address_line_1 = $request->address_line_1;
            $project->address_line_2 = $request->address_line_2;
            $project->address_line_2 = $request->address_line_2;
            $project->country = $request->country;
            $project->state = $request->state;
            $project->city = $request->city;
            $project->city = $request->city;
            $project->postal_code = $request->postal_code;
            $project->tags = $request->input;
            $project->status = $request->has('is_active') ? 1 : 0;
            $project->save();

            $project_id = $project->id;

            $user_project = new UserProject();
            if (isset($user_project)) {
                $user_project->user_id = $request->user_id;
                $user_project->project_id = $project_id;
                $user_project->save();
            } else {
                return back()->with('error', 'Userproject does not exist');
            }

            $project_amenities = new ProjectAmenity();
            if (isset($project_amenities)) {
                $project_amenities->project_id = $project_id;
                $project_amenities->amenity_id = $request->amenity_id;
                $project_amenities->save();
            } else {
                return back()->with('error', 'projectAmenities does not exist');
            }

            return redirect()->route('project.index')->with('success', 'project Add Successfully');
        } else {
            return back()->with('error', 'project does not exist');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $project = Project::find($id);

        if (!$project) {
            return redirect()->back()->with('error', 'Project not found.');
        }


        $user_project = UserProject::where('project_id', $id)->first();

        $project_notes = ProjectNotes::all();

        $project_amenities = ProjectAmenity::where('project_id', $id)->first();

        return view('users.project.show', compact('project', 'user_project', 'project_notes', 'project_amenities'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $project = Project::with('its_company', 'its_country', 'its_states', 'its_city')->findOrFail($id);
        $companies = Company::all();
        $countries = Country::all();
        $states = States::all();
        $cities = City::all();
        $users = User::all();
        $user_project = UserProject::all();
        $amenities = Amenities::all();
        $project_amenities = ProjectAmenity::all();
        return view('users.project.edit', compact('companies', 'project', 'countries', 'states', 'cities', 'users', 'user_project', 'amenities', 'project_amenities'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {

        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'company_id' => 'required|exists:companies,id',
            'nature' => 'required',
            'user_id' => 'required|exists:users,id',
            'notes' => 'nullable|string',
            'amenity_id' => 'required|exists:amenities,id',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $project = Project::find($id);

        if ($project) {
            $project->company_id = $request->company_id;
            $project->title = $request->title;
            $project->description = $request->description;
            $project->nature = $request->nature;
            $project->start_date = $request->start_date;
            $project->address_line_1 = $request->address_line_1;
            $project->address_line_2 = $request->address_line_2;
            $project->country = $request->country;
            $project->state = $request->state;
            $project->city = $request->city;
            $project->postal_code = $request->postal_code;
            $project->tags = $request->input;
            $project->status = $request->has('is_active') ? 1 : 0;
            $project->save();


            $user_project = UserProject::where('project_id', $project->id)->first();
            if ($user_project) {
                $user_project->user_id = $request->user_id;
            } else {

                $user_project = new UserProject();
                $user_project->project_id = $project->id;
                $user_project->user_id = $request->user_id;
            }
            $user_project->save();


            $project_amenities = ProjectAmenity::where('project_id', $project->id)->first();
            if ($project_amenities) {
                $project_amenities->amenity_id = $request->amenity_id;
            } else {

                $project_amenities = new ProjectAmenity();
                $project_amenities->project_id = $project->id;
                $project_amenities->amenity_id = $request->amenity_id;
            }
            $project_amenities->save();

            return redirect()->route('project.index')->with('success', 'Project has been updated successfully');
        } else {
            return back()->with('error', 'Project does not exist');
        }
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $project = Project::find($id);
        if (isset($project)) {
            $project->delete();
            ProjectNotes::where('project_id', $id)->delete();
            UserProject::where('project_id', $id)->delete();
            ProjectAmenity::where('project_id', $id)->delete();
            Property::where('project_id', $id)->delete();
            return redirect()->back()->with('success', 'Project has been deleted successfully.');
        } else {
            return back()->with('error', 'Project does not exist');
        }
    }

    public function updateProjectStatus(Request $request, $id)
    {
        if ($request->has('new_status')) {
            $project = Project::find($id);

            if ($project) {
                $project->status = $request->new_status;
                $project->save();
                return response()->json(['status' => 'success', 'message' => 'Project status updated successfully']);
            } else {
                return response()->json(['status' => 'error', 'message' => 'Project not found'], 404);
            }
        } else {
            return response()->json(['status' => 'error', 'message' => 'Missing status value'], 404);
        }
    }

    public function addProjectNotes(Request $request, $project_id)
    {

        $validator = Validator::make($request->all(), [
            'notes' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $project_note = new ProjectNotes();
        if (isset($project_note)) {
            $project_note->project_id = $project_id;


            $currentUserId = getAdminId();
            $project_note->created_by = $currentUserId->created_by;
            $project_note->notes = $request->notes;
            $project_note->save();


            return redirect()->back()->with('success-projectnote', 'Project Note added successfully');
        } else {
            return redirect()->back()->with('error-projectnote', 'Project Note does not exist');
        }
    }


    public function projectNotes_index(Request $request)
    {
        if ($request->ajax()) {

            $request_data = $request->all();

            // avoid zero column as it's checkbox so we can't sort by it
            if ($request->has('order') && $request->order[0]['column'] != 0) {
                $sort_column_number = $request->order[0]['column'];
                $sort_column_dir = $request->order[0]['dir'];
                $sort_column_key = $request->columns[$sort_column_number]['data'];
            }

            $main_query = ProjectNotes::query();
            $query = $main_query->where('project_id', $request->project_id);
            $data = $query->with('get_project')->get();
            $count_total = $main_query->count();
            $count_filter = $count_total;
            return DataTables::of($data)



                ->addColumn('project_id', function ($row) {
                    return isset($row->get_project)  ? $row->get_project->title : '';
                })
                ->addColumn('notes', function ($row) {
                    return $row->notes;
                })
                ->addColumn('created_by', function ($row) {
                    return  isset($row->get_current_user) ? $row->get_current_user->first_name : '';
                })
                ->addColumn('date', function ($row) {
                    return formatDate($row->created_at, 'Y/m/d H:i:s');
                })

                ->addColumn('action', function ($row) {

                    if ($row->is_admin !== 1) {
                        $project_note = ProjectNotes::find($row->id);
                        return view('users.project.partially.projectnotes-delete', compact('row', 'project_note'));
                    }
                })
                ->rawColumns(['action'])
                ->with([
                    "recordsTotal"    => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->make(true);
        }
        return view('users.user.show');
    }


    public function ProjectNotesUpdate(Request $request, $project_id)
    {


        $validator = Validator::make($request->all(), [
            'notes' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $project_note = ProjectNotes::find($project_id);
        if (isset($project_note)) {

            $originalNotes = $project_note->getOriginal('notes');

            $project_note->notes = $request->notes;
            $currentUserId =  getAdminId();
            $project_note->created_by = $currentUserId->created_by;
            $project_note->save();


            return redirect()->back()->with('success-projectnote', 'Project Note Updated successfully');
        } else {
            return redirect()->back()->with('error-projectnote', 'Project does not exist');
        }
    }

    public function ProjectNotesDelete(string $id)
    {
        $project_note = ProjectNotes::find($id);
        if (isset($project_note)) {
            $userId = $project_note->project_id;
            $project_note->delete();

            return redirect()->back()->with('success-projectnote', 'Project Notes has been deleted successfully.');
        } else {
            return back()->with('error-projectnote', 'Project Notes does not exist');
        }
    }
}