<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\Label;
use App\Models\Client;
use App\Models\Status;
use App\Models\Setting;
use App\Models\Milestone;
use Illuminate\Http\Request;
use App\Models\Notification;
use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class ProjectController extends Controller
{
    public function index(Request $request)
    {
        $projectsQuery = Project::with('labels', 'client');

        if ($request->filled('label_id')) {
            $projectsQuery->whereHas('labels', function ($query) use ($request) {
                $query->where('label_id', $request->label_id);
            });
        }

        if ($request->filled('start_date')) {
            $projectsQuery->where('start_date', '>=', $request->start_date);
        }

        if ($request->filled('deadline')) {
            $projectsQuery->where('deadline', '<=', $request->deadline);
        }

        $projects = $projectsQuery->get();
        $labels = Label::all();
        $clients = Client::all();
        $statuses = Status::all();

        return view('admin.projects.index', compact('projects', 'labels', 'clients', 'statuses'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'required|date',
            'deadline' => 'required|date',
            'price' => 'required|numeric',
            'labels' => 'array',
            'status_id' => 'nullable|exists:statuses,id',
        ]);

        $project = new Project();
        $project->title = $request->title;
        $project->client_id = $request->client_id;
        $project->description = $request->description;
        $project->start_date = $request->start_date;
        $project->deadline = $request->deadline;
        $project->price = $request->price;
        $project->status_id = $request->status_id;
        $project->save();

        $project->labels()->sync($request->labels);

        // Create a new notification
        $clientUser = DB::table('users')->where('client_id', $request->client_id)->first();
        $notification = Notification::create([
            'title' => "A New Project Created",
            'body' => 'Project:- '.$request->title,
            'send_at' => now(), // Current date and time
            'sent' => $request->input('sent', false), // Default to false if not provided
            'url' => 'client.projects.index', // Example route for redirection
            'from_id' => Auth::id(), // Authenticated user's ID
            'to_id' => $clientUser->id, // Client ID for to_id
        ]);


        // Check the email notification setting
        $emailSettings = DB::table('email_notification_settings')->first();

        // Send email if new_project_mail_client is set to 1
        if ($emailSettings && $emailSettings->new_project_mail_client == 1) {
            if ($clientUser && $clientUser->email) {
                $data = [
                    'title' => $request->title,
                    'description' => $request->description,
                    'start_date' => $request->start_date,
                    'deadline' => $request->deadline,
                    'client_name' => $clientUser->name,
                ];

                // Send email
                Mail::send([], [], function ($message) use ($clientUser, $data) {
                    $message->to($clientUser->email)
                        ->subject('New Project Created: ' . $data['title'])
                        ->html("
                            <h1>New Project Created</h1>
                            <p>Dear {$clientUser->name},</p>
                            <p>A new project has been created for you:</p>
                            <ul>
                                <li><strong>Title:</strong> {$data['title']}</li>
                                <li><strong>Description:</strong> {$data['description']}</li>
                                <li><strong>Start Date:</strong> {$data['start_date']}</li>
                                <li><strong>Deadline:</strong> {$data['deadline']}</li>
                            </ul>
                            <p>Please login to view more details.</p>
                        ");
                });
            }
        }

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

    public function edit($id)
    {
        $project = Project::with('labels', 'client')->findOrFail($id);
        $labels = Label::all();
        $clients = Client::all();
        $statuses = Status::all();
        // Get only the milestones that belong to the current project
        $milestones = Milestone::where('project_id', $id)->get();
        $settings = Setting::first();
        
        return view('admin.projects.edit', compact('project', 'labels', 'clients', 'statuses', 'milestones', 'settings'));
    }    


    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'required|date',
            'deadline' => 'required|date',
            'price' => 'required|numeric',
            'labels' => 'array',
            'status_id' => 'nullable|exists:statuses,id',
        ]);

        $project = Project::findOrFail($id);
        $project->title = $request->title;
        $project->client_id = $request->client_id;
        $project->description = $request->description;
        $project->start_date = $request->start_date;
        $project->deadline = $request->deadline;
        $project->price = $request->price;
        $project->status_id = $request->status_id;
        $project->save();

        $project->labels()->sync($request->labels);

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

    public function destroy($id)
    {
        $project = Project::findOrFail($id);
        $project->delete();
        return redirect()->route('projects.index')->with('success', 'Project deleted successfully');
    }


    public function addMilestone(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'status' => 'required|in:complete,incomplete',
            'cost' => 'required|numeric',
            'summary' => 'nullable|string',
            'percentage_done' => 'required|integer|min:0|max:100',
            'project_id' => 'required|exists:projects,id',
        ]);

        Milestone::create($request->all());

        // Create a new notification
        $projects = DB::table('projects')->where('id', $request->project_id)->first();
        $clientUser = DB::table('users')->where('client_id', $projects->client_id)->first();
        $notification = Notification::create([
            'title' => "A New Milestone Created",
            'body' => 'Milestone:- '.$request->title,
            'send_at' => now(), // Current date and time
            'sent' => $request->input('sent', false), // Default to false if not provided
             'url' => route('client.projects'),
            'from_id' => Auth::id(), // Authenticated user's ID
            'to_id' => $clientUser->id, // Client ID for to_id
        ]);


        // Check the email notification setting
        $emailSettings = DB::table('email_notification_settings')->first();

        // Send email if new_milestones_mail_client is set to 1
        if ($emailSettings && $emailSettings->new_milestones_mail_client == 1) {
            if ($clientUser && $clientUser->email) {
                $data = [
                    'title' => $request->title,
                    'cost' => $request->cost,
                    'summary' => $request->summary,
                    'percentage_done' => $request->percentage_done,
                    'client_name' => $clientUser->name,
                ];

                // Send email
                Mail::send([], [], function ($message) use ($clientUser, $data) {
                    $message->to($clientUser->email)
                        ->subject('New Milestone Created: ' . $data['title'])
                        ->html("
                            <h1>New Milestone Created</h1>
                            <p>Dear {$clientUser->name},</p>
                            <p>A new milestone has been created for your project:</p>
                            <ul>
                                <li><strong>Title:</strong> {$data['title']}</li>
                                <li><strong>Cost:</strong> {$data['cost']}</li>
                                <li><strong>Summary:</strong> {$data['summary']}</li>
                                <li><strong>Percentage Done:</strong> {$data['percentage_done']}%</li>
                            </ul>
                            <p>Please login to view more details.</p>
                        ");
                });
            }
        }


        return response()->json(['success' => 'Milestone added successfully']);
    }

    public function updateMilestone(Request $request, Milestone $milestone)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'status' => 'required|in:complete,incomplete',
            'cost' => 'required|numeric',
            'summary' => 'nullable|string',
            'percentage_done' => 'required|integer|min:0|max:100',
        ]);

        $milestone->update($request->all());

        return redirect()->back()->with('success', 'Milestone updated successfully');
    }

    public function deleteMilestone(Milestone $milestone)
    {
        $milestone->delete();

        return redirect()->back()->with('success', 'Milestone deleted successfully');

    }
}
