<?php

namespace App\Http\Controllers;

use App\Models\Project; 
use App\Models\Projects_Required; 
use App\Models\project_needs; 
use App\Models\ProjectRequiredAttachments; 
use App\Models\ProjectReview; 
use App\Models\ProjectAttachments; 
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
        $projects = DB::table('projects')->where('organization_id', Auth::user()->referencesUser)->count();
       
      if(Auth::user()->referencesUser == "admin"){
         $departments = 'administrator';
         $sectors = DB::table('sectors')->get();
          $dept = DB::table('departments')
         ->join('sectors', 'sectors.id', '=', 'departments.sector_id')
         ->get(['departments.*','sectors.sectorName']);
      }else{
         $dept = DB::table('departments')
         ->join('sectors', 'sectors.id', '=', 'departments.sector_id')
         ->where('departments.id', Auth::user()->referencesUser)->first(['sectors.sectorName']);
        $sectors = DB::table('sectors')->get();
        $departments = $dept->sectorName;
      }
       
         $grantstotalCost = DB::table('grants')
           ->where('organization_id', Auth::user()->referencesUser)
            ->sum('grant_amount');

        $donationstotal = DB::table('donations')
           ->where('organization_id', Auth::user()->referencesUser)
            ->sum('quantity');
        
         $lastGrants = DB::table('grants')
        ->join('sectors', 'sectors.id', '=', 'grants.sector_id')
        ->where('organization_id', Auth::user()->referencesUser)
        ->orderBy('grants.created_at', 'desc')
                        ->take(5)
                        ->get(['grants.*','sectors.sectorName']);
       return view('projects.index',compact('dept','sectors','departments','projects','grantstotalCost','donationstotal'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
       $sectors = DB::table('sectors')->get();
        return view('projects.create', compact('sectors'));
    }

    /**
     * Store a newly created resource in storage.
     */
    /*
    public function store(Request $request)
    {
        //
         $request->validate([
        'organization_id' => 'required|exists:users,referencesUser',
        'title'           => 'required|string|max:255',
        'description'     => 'required|string|min:10',
        'start_date'      => 'required|date',
        'end_date'        => 'required|date|after_or_equal:start_date',
        'TotalCost'       => 'required|numeric|min:0',
        'currency'        => 'required|in:USD,EUR,SDG,SAR',
        'sector_id'        => 'required|exists:sectors,id',
         'user_id'        => 'required',
    ], [
        'organization_id.required' => 'يجب تحديد المنظمة.',
        'title.required'           => 'اسم المشروع مطلوب.',
        'description.required'     => 'الوصف مطلوب.',
        'start_date.required'      => 'تاريخ البداية مطلوب.',
        'end_date.required'        => 'تاريخ النهاية مطلوب.',
        'end_date.after_or_equal'  => 'تاريخ النهاية يجب أن يكون بعد أو يساوي تاريخ البداية.',
        'TotalCost.required'       => 'التكلفة مطلوبة.',
        'TotalCost.numeric'        => 'التكلفة يجب أن تكون رقم.',
        'currency.required'        => 'العملة مطلوبة.',
        'sector_id.required'        => 'القطاع مطلوبة.',
        'currency.in'              => 'العملة يجب أن تكون واحدة من (USD, EUR, SDG, SAR).',
        'user_id.required'        => 'العملة مطلوبة.',
    ]);

    
    Project::create($request->all());
      return back()->with('success', 'تم الحفظ بنجاح ...  ..!');

    }
*/


public function store(Request $request)
{
    // ✅ التحقق من صحة البيانات
    //dd($request);
    $request->validate([
        'department_id'   => 'required|exists:departments,id',
        'user_id'         => 'required|exists:users,id',
        'projects_title'  => 'required|string|max:255',
        'description'     => 'nullable|string',
        'start_date'      => 'required|date',
        'end_date'        => 'required|date|after_or_equal:start_date',
        'total_cost'      => 'required|numeric',
        'currency'        => 'required|in:USD,EUR,SDG,SAR',
        'Project_Document'=> 'nullable|file|mimes:pdf|max:5120',
    ], [
        'projects_title.required' => 'عنوان المشروع مطلوب',
        'end_date.after_or_equal' => 'تاريخ الانتهاء يجب أن يكون بعد أو يساوي تاريخ البداية',
        'Project_Document.mimes'  => 'يجب أن يكون الملف من نوع PDF ',
    ]);

    // ✅ رفع الملف إذا وجد
    $filePath = null;
    if ($request->hasFile('Project_Document')) {
        $filePath = $request->file('Project_Document')->store('projects_documents', 'public');
    }

    // ✅ إنشاء سجل جديد
    $project = new Projects_Required();
    $project->department_id   = $request->department_id;
    $project->user_id         = $request->user_id;
    $project->projects_title  = $request->projects_title;
    $project->description     = $request->description;
    $project->start_date      = $request->start_date;
    $project->end_date        = $request->end_date;
    $project->total_cost      = $request->total_cost;
    $project->currency        = $request->currency;
    $project->Project_Document= $filePath;
    $project->save();



    // ✅ إعادة التوجيه مع رسالة نجاح
    return redirect()->route('projects.index')
                     ->with('success', 'The project was successfully saved...');
}



public function Requirement_store(Request $request)
{
    // ✅ التحقق من صحة البيانات
    $request->validate([
        'user_id'         => 'required|exists:users,id',
        'project_id'      => 'required|exists:projects__requireds,id',
        'need_description'=> 'required|string|max:255',
        'location_id'     => 'required|exists:states,id',
        'priority'        => 'required|in:High,Medium,Low',
        'TotalCost'       => 'nullable|numeric',
        'currency'        => 'required|in:USD,EUR,SDG,SAR',
    ], [
        'need_description.required' => 'وصف الحاجة مطلوب',
        'location_id.required'      => 'الموقع مطلوب',
        'priority.required'         => 'الأولوية مطلوبة',
    ]);

    // ✅ إنشاء سجل جديد
    $requirement = new project_needs();
    $requirement->user_id          = $request->user_id;
    $requirement->project_id       = $request->project_id;
    $requirement->need_description = $request->need_description;
    $requirement->location_id      = $request->location_id;
    $requirement->priority         = $request->priority;
    $requirement->TotalCost        = $request->TotalCost;
    $requirement->currency         = $request->currency;
    $requirement->save();

    // ✅ إعادة التوجيه مع رسالة نجاح
     $project_Id = Crypt::encrypt($request->project_id);
    return redirect()->route('projects.show-Project', $project_Id)
                     ->with('success', 'The project requirements were successfully saved.');
}


//=====================================================================================
     public function getNeedprojectData($Project_id)
    {
        $project_id = Crypt::decrypt($Project_id);
        //$project_id = $Project_id;
        $projectNeeds = DB::table('project_needs')
        ->join('states', 'states.id', '=', 'project_needs.location_id')
        ->join('projects__requireds', 'projects__requireds.id', '=', 'project_needs.project_id')
        ->where('project_needs.project_id', $project_id)
        ->get(['project_needs.*','states.StatesName','projects__requireds.flg']);

        return DataTables::of($projectNeeds)
        ->addColumn('action', function ($projectNeeds) {
            $Project_id = Crypt::encrypt($projectNeeds->id);
                if($projectNeeds->flg == 'In_review' AND Auth::user()->referencesUser == "admin")
            {
                return 'In Review';
        }else 
        if(($projectNeeds->flg == 'Edit' OR $projectNeeds->flg == 'N') AND Auth::user()->referencesUser !== "admin")
            {
                return '<a href="../Delete-Need/'.$Project_id.'" class="btn btn-sm btn-danger">
                        <i class="fa fas fa-remove" "></i>
                        </a>
                    ';
        }
        /*else
        {
                    return '<a href="../Delete-Need/'.$Project_id.'" class="btn btn-sm btn-danger">
                        <i class="fa fas fa-remove" "></i>
                        </a>
                    ';
            }*/
        })
        ->addColumn('action2', function ($projectNeeds) {
            $projectNeedspriority = $projectNeeds->priority;
            if($projectNeedspriority == "Medium")
            {
                return '
                <a href="show-Task-Activity/'.$projectNeedspriority.'" 
                style="background-color: #fdfd00;color: #9b9b00;"
                class="btn btn-sm btn-primary">Medium </a>
            ';
        }else
        if($projectNeedspriority == "High"){
             return '
                <a href="show-Task-Activity/'.$projectNeedspriority.'" 
                style="background-color: #da3f4cff;color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">High</a>
            ';
            }
            else
        if($projectNeedspriority == "Low"){
             return '
                <a href="show-Task-Activity/'.$projectNeedspriority.'"
                style="background-color: #3f9cdaff;color: #fcf8f8ff;"
                class="btn btn-sm btn-info">Low</a>
            ';
            }
        })
        
        ->addColumn('action3', function ($projectNeeds) {
            $projectNeedsStatus = $projectNeeds->status;
            if($projectNeedsStatus == "Pending")
            {
                return '
                <a href="show-Task-Activity/'.$projectNeedsStatus.'" 
                style="background-color: #fdfd00;color: #9b9b00;"
                class="btn btn-sm btn-primary">Pending </a>
            ';
        }else
        if($projectNeedsStatus == "Fulfilled"){
             return '
                <a href="show-Task-Activity/'.$projectNeedsStatus.'"
                class="btn btn-sm btn-success">Fulfilled</a>
            ';
            }
        })
        ->rawColumns(['action','action2','action3']) // allow HTML rendering
    //    ->rawColumns(['action2']) // allow HTML rendering
        ->make(true);
    }

    //=============================================================================



    /**
     * Display the specified resource.
     */
    public function show_Project(string $id)
    {
        //
        $project_Id = Crypt::decrypt($id);
         $states = DB::table('states')->get();
       $ProjectData_id   = Projects_Required::where('id', $project_Id)->first();
      
                   
                        $sectors = DB::table('sectors')->get();

         $projects = DB::table('projects')->where('organization_id', Auth::user()->referencesUser)->count();
       
      if(Auth::user()->referencesUser == "admin"){
        // $departments = 'administrator';
         $dept = DB::table('departments')
                        ->join('sectors', 'sectors.id', '=', 'departments.sector_id')
                        ->join('projects__requireds', 'projects__requireds.department_id', '=', 'departments.id')
                        ->where('projects__requireds.id', $project_Id)->first(['sectors.sectorName']);
                   // echo  Auth::user()->referencesUser;
            $departments = $dept->sectorName;
         $sectors = DB::table('sectors')->get();
      }else{
         $dept = DB::table('departments')
         ->join('sectors', 'sectors.id', '=', 'departments.sector_id')
         ->where('departments.id', Auth::user()->referencesUser)->first(['sectors.sectorName']);
        $sectors = DB::table('sectors')->get();
        $departments = $dept->sectorName;
      }
       
         $grantstotalCost = DB::table('grants')
           ->where('organization_id', Auth::user()->referencesUser)
            ->sum('grant_amount');

        $donationstotal = DB::table('donations')
           ->where('organization_id', Auth::user()->referencesUser)
            ->sum('quantity');
        
         $lastGrants = DB::table('grants')
        ->join('sectors', 'sectors.id', '=', 'grants.sector_id')
        ->where('organization_id', Auth::user()->referencesUser)
        ->orderBy('grants.created_at', 'desc')
                        ->take(5)
                        ->get(['grants.*','sectors.sectorName']);

        $ProjectData_Attachments   = ProjectRequiredAttachments::where('project_id', $project_Id)->get();
         $ProjectAttachments   = ProjectAttachments::where('project_id', $project_Id)->get();

        $ProjectData_Review   = ProjectReview::where('project_id', $project_Id)->get();

      $ProjectNeed_Data  = project_needs::where('project_id', $project_Id)->count();
        

        return view('projects.show' , compact('ProjectNeed_Data','grantstotalCost','donationstotal','projects','departments','ProjectAttachments','ProjectData_Review','ProjectData_id','states','ProjectData_Attachments'));
    }

    public function getDatauser()
    {
       // $userdata = user::select(['id', 'name', 'email']);
        $userdata = User::all();
        
        return DataTables::of($userdata)->make(true);
    }

    public function getData()
    {
        //$ProjectData   = Project::all();
         $user_role = DB::table('role_users')->where('user_id', Auth::user()->id)->first();
         if($user_role->role_id == 1) //============admin=========================
    {
         $ProjectData = DB::table('projects__requireds')
                    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
                ->get(['projects__requireds.*']);
    }else
    if($user_role->role_id == 2) //=====================================
    {
       $ProjectData = DB::table('projects__requireds')
    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
    //->join('sponsors', 'sponsors.id', '=', 'projects__requireds.sponsors_id')
   //->where('projects__requireds.department_id', Auth::user()->referencesUser)
    ->get(['projects__requireds.*']);
    }
    if($user_role->role_id == 3) //=====================================
    {
     $ProjectData = DB::table('projects__requireds')
    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
    //->join('sponsors', 'sponsors.id', '=', 'projects__requireds.sponsors_id')
   ->where('projects__requireds.department_id', Auth::user()->referencesUser)
    ->get(['projects__requireds.*']);
    } 
    

return DataTables::of($ProjectData)
    ->addColumn('action2', function ($row) {
        if ($row->status == "In_progress") {
            return '
                <a href="../show-Project/'.$row->status.'" 
                style="background-color: #fdfd00;color: #9b9b00;"
                class="btn btn-sm btn-primary">جاري التنفيذ</a>
            ';
        } elseif ($row->status == "Planned") {
            return '
                <a href="../show-Project/'.$row->status.'" 
                style="background-color: #da3f4cff;color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">مؤجل</a>
            ';
        } elseif ($row->status == "Completed") {
            return '
                <a href="../show-Project/'.$row->status.'"
                class="btn btn-sm btn-success">انتهاء</a>
            ';
        }
    })
    ->addColumn('action', function ($row) {
        if ($row->flg == "In_review") {
            return '
                <a href="../show-Project/'.$row->flg.'" 
                style="background-color: #fdfd00;color: #5f6213;"
                class="btn btn-sm btn-primary">Review</a>
            ';
        } elseif ($row->flg == "Not_Satisfy") {
            return '<a href="../show-Project/'.$row->flg.'" 
                style="background-color: #da3f4cff;color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">Not Satisfy</a>
            ';
        } elseif ($row->flg == "Satisfy") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                class="btn btn-sm btn-success">Satisfy</a>
            ';
        } elseif ($row->flg == "N") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                style="background-color: rgb(38, 181, 115);color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">New</a>
            ';
        }elseif ($row->flg == "Edit") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                style="background-color: rgba(241, 201, 89, 1);color: #030303ff;"
                class="btn btn-sm btn-primary">Edit</a>
            ';
        }
    })
    ->addColumn('Project_Document', function ($row) {
    if ($row->Project_Document) {
        return '<a href="'.asset('storage/'.$row->Project_Document).'" target="_blank" 
                class="btn btn-sm btn-danger">
                <i class="fa fa-file-pdf"></i> view 
                </a>';
    } else {
        return '<span class="text-muted">لا يوجد ملف</span>';
    }
})
->addColumn('view', function ($row) {
    $project_Id = Crypt::encrypt($row->id);
    return '<a href="'.route('projects.show-Project', $project_Id).'" 
            class="btn btn-sm btn-primary">
            <i class="fa fa-eye"></i> View
            </a>';
})
    ->rawColumns(['action2','action','Project_Document','view'])// دمج الأعمدة هنا
    ->make(true);

    }

//=======================================for admin ====

    public function getDataadmin()
    {
        //$ProjectData   = Project::all();
        $deptId = request()->get('department_id'); 
         $user_role = DB::table('role_users')->where('user_id', Auth::user()->id)->first();
         if($user_role->role_id == 1) //============admin=========================
    {
         $ProjectData = DB::table('projects__requireds')
                    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
                    ->where('projects__requireds.department_id', $deptId)
                ->get(['projects__requireds.*']);
    }else
    if($user_role->role_id == 2) //=====================================
    {
       $ProjectData = DB::table('projects__requireds')
    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
    //->join('sponsors', 'sponsors.id', '=', 'projects__requireds.sponsors_id')
   //->where('projects__requireds.department_id', Auth::user()->referencesUser)
    ->get(['projects__requireds.*']);
    }
    if($user_role->role_id == 3) //=====================================
    {
     $ProjectData = DB::table('projects__requireds')
    ->join('departments', 'departments.id', '=', 'projects__requireds.department_id')
    //->join('sponsors', 'sponsors.id', '=', 'projects__requireds.sponsors_id')
   ->where('projects__requireds.department_id', Auth::user()->referencesUser)
    ->get(['projects__requireds.*']);
    } 
    

return DataTables::of($ProjectData)
    ->addColumn('action2', function ($row) {
        if ($row->status == "In_progress") {
            return '
                <a href="../show-Project/'.$row->status.'" 
                style="background-color: #fdfd00;color: #9b9b00;"
                class="btn btn-sm btn-primary">جاري التنفيذ</a>
            ';
        } elseif ($row->status == "Planned") {
            return '
                <a href="../show-Project/'.$row->status.'" 
                style="background-color: #da3f4cff;color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">مؤجل</a>
            ';
        } elseif ($row->status == "Completed") {
            return '
                <a href="../show-Project/'.$row->status.'"
                class="btn btn-sm btn-success">انتهاء</a>
            ';
        }
    })
    ->addColumn('action', function ($row) {
        if ($row->flg == "In_review") {
            return '
                <a href="../show-Project/'.$row->flg.'" 
                style="background-color: #fdfd00;color: #5f6213;"
                class="btn btn-sm btn-primary">Review</a>
            ';
        } elseif ($row->flg == "Not_Satisfy") {
            return '<a href="../show-Project/'.$row->flg.'" 
                style="background-color: #da3f4cff;color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">Not Satisfy</a>
            ';
        } elseif ($row->flg == "Satisfy") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                class="btn btn-sm btn-success">Satisfy</a>
            ';
        } elseif ($row->flg == "N") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                style="background-color: rgb(38, 181, 115);color: #fcf8f8ff;"
                class="btn btn-sm btn-primary">New</a>
            ';
        }elseif ($row->flg == "Edit") {
            return '
                <a href="../show-Project/'.$row->flg.'"
                style="background-color: rgba(241, 201, 89, 1);color: #030303ff;"
                class="btn btn-sm btn-primary">Edit</a>
            ';
        }
    })
    ->addColumn('Project_Document', function ($row) {
    if ($row->Project_Document) {
        return '<a href="'.asset('storage/'.$row->Project_Document).'" target="_blank" 
                class="btn btn-sm btn-danger">
                <i class="fa fa-file-pdf"></i> view 
                </a>';
    } else {
        return '<span class="text-muted">لا يوجد ملف</span>';
    }
})
->addColumn('view', function ($row) {
    $project_Id = Crypt::encrypt($row->id);
    return '<a href="'.route('projects.show-Project', $project_Id).'" 
            class="btn btn-sm btn-primary">
            <i class="fa fa-eye"></i> View
            </a>';
})
    ->rawColumns(['action2','action','Project_Document','view'])// دمج الأعمدة هنا
    ->make(true);

    }
//===================================================


    /**
     * Show the form for editing the specified resource.
     */
    public function Send_projects(string $id)
    {
        //
         $project_Id = Crypt::decrypt($id);
         $requirement = Projects_Required::findOrFail($project_Id);
        $requirement->flg = 'In_review';
        $requirement->save();

    return redirect()->back()->with('success', 'The project has been sent for review.');
    }

     public function Save_Review_projects(Request $request)
        {
            echo 'Save_Review_projects';
        }

public function saveReviewProjects(Request $request)
{
    // ✅ التحقق من صحة البيانات
    $request->validate([
        'project_id'     => 'required|exists:projects__requireds,id',
        'user_id'        => 'required|exists:users,id',
        'description'    => 'required|string',
        'filename'       => 'nullable|array',
        'filename.*'     => 'nullable|string',
    ]);

    // ✅ حفظ المراجعة في جدول project_reviews
    $review = ProjectReview::create([
        'project_id'        => $request->project_id,
        'Review_description'=> $request->description,
        'flg'               => 'in review', // الحالة الافتراضية
        'user_id'           => $request->user_id,
    ]);

    // ✅ حفظ المرفقات في جدول project_required_attachments
    if (!empty($request->filename)) {
    foreach ($request->filename as $file) {
        ProjectRequiredAttachments::create([
            'reviews_id'          => $review->id,
            'project_id'          => $request->project_id,
            'required_attachments'=> $file,
            'flg'                 => 'attached',
            'user_id'             => $request->user_id,
        ]);
    }
}

        $project = Projects_Required::find($request->project_id);
        $project->flg = 'Edit';
        $project->save();

    return redirect()->route('projects.index')
                     ->with('success', 'The review and attachments were successfully saved.');
}


public function uploadRequirementDocument(Request $request)
{
    // ✅ التحقق من صحة البيانات
    $request->validate([
        'file_id'      => 'required|exists:project_required_attachments,id',
        'project_id'  => 'required|exists:projects__requireds,id',
        'file_attachments'   => 'required|file|mimes:pdf,jpg,jpeg,png|max:3072', // 3MB
        'userid'      => 'required|exists:users,id',
    ]);

    // ✅ حفظ الملف في مجلد التخزين
    $path = $request->file('file_attachments')->store('project_files', 'public');

    // ✅ إنشاء سجل جديد في جدول project_attachments
    ProjectAttachments::create([
        'project_id'       => $request->project_id,
        'file_id'          => $request->file_id,
        'file_attachments' => $path,
        'flg'              => 'uploaded',
        'user_id'          => $request->userid,
    ]);

    return redirect()->back()->with('success', 'The document was successfully uploaded and saved.');
}



    public function edit(string $id)
    {
        //
    }

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function destroyRequirementDocument($id)
    {
        $file = ProjectAttachments::findOrFail($id);

      
        Storage::disk('public')->delete($file->file_attachments);

        
        $file->delete();

        return redirect()->back()->with('success', 'The file has been successfully deleted ✅');
    }

     public function Delete_Need($id)
    {

        $project_Id = Crypt::decrypt($id);

       project_needs::where('id', $project_Id)->delete();

    /*  
        Storage::disk('public')->delete($file->file_attachments);

        
        $file->delete();
*/
        return redirect()->back()->with('success', 'The Record has been successfully deleted ✅');
   
    }
}
