<?php

namespace App\Http\Controllers;

use App\Models\Contract;
use App\Models\Client;
use App\Models\Project;
use App\Models\Setting;
use Carbon\Carbon;
use App\Models\Notification;
use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class ContractController extends Controller
{
    public function index()
    {
        $contracts = Contract::with('client', 'project')->get();
        $clients = Client::all();
        $projects = Project::all();
        $setting = Setting::first();
    
        // Total Contracts
        $totalContracts = $contracts->sum('amount');
    
        // This Month's Total Contracts
        $thisMonthTotalContracts = Contract::whereYear('created_at', Carbon::now()->year)
                                            ->whereMonth('created_at', Carbon::now()->month)
                                            ->sum('amount');
    
        // This Week's Total Contracts
        $thisWeekTotalContracts = Contract::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
                                            ->sum('amount');
    
        // Last 30 Days' Total Contracts
        $last30DaysTotalContracts = Contract::where('created_at', '>=', Carbon::now()->subDays(30))
                                             ->sum('amount');
    
        return view('admin.contracts.index', compact(
            'contracts', 
            'clients', 
            'projects', 
            'setting', 
            'totalContracts', 
            'thisMonthTotalContracts', 
            'thisWeekTotalContracts', 
            'last30DaysTotalContracts'
        ));
    }
    

    // Show the form for creating a new contract
    public function create()
    {
        $clients = Client::all();
        $projects = Project::all();
        return view('contracts.create', compact('clients', 'projects'));
    }

    // Store a newly created contract in storage
    public function store(Request $request)
    {
        $this->validateContract($request);

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

        // Create a new notification
        $clientUser = DB::table('users')->where('client_id', $request->client_id)->first();
        $notification = Notification::create([
            'title' => "A New Contract Created",
            'body' => 'Contract:- '.$request->subject,
            'send_at' => now(), // Current date and time
            'sent' => $request->input('sent', false), // Default to false if not provided
            'url' => 'client.contracts', // 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 for contracts_mail_client
        $emailSettings = DB::table('email_notification_settings')
        ->where('client_id', $request->client_id)->first();

        // Send email if contracts_mail_client is set to 1
        if ($emailSettings && $emailSettings->contracts_mail_client == 1) {
            if ($clientUser && $clientUser->email) {
                $data = [
                    'subject' => $request->subject,
                    'client_name' => $clientUser->name,
                ];

                // Send email
                Mail::send([], [], function ($message) use ($clientUser, $data) {
                    $message->to($clientUser->email)
                        ->subject('New Contract Created: ' . $data['subject'])
                        ->html("
                            <h1>New Contract Created</h1>
                            <p>Dear {$clientUser->name},</p>
                            <p>A new contract has been created for you:</p>
                            <ul>
                                <li><strong>Subject:</strong> {$data['subject']}</li>
                            </ul>
                            <p>Please login to view more details.</p>
                        ");
                });
            }
        }

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

    // Show the form for editing the specified contract
    public function edit(Contract $contract)
    {
        $clients = Client::all();
        $projects = Project::all();
        return view('contracts.edit', compact('contract', 'clients', 'projects'));
    }

    // Update the specified contract in storage
    public function update(Request $request, Contract $contract)
    {
        $this->validateContract($request);

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

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

    // Remove the specified contract from storage
    public function destroy(Contract $contract)
    {
        $contract->delete();

        return redirect()->route('contracts.index')->with('success', 'Contract deleted successfully.');
    }

    // Consolidated validation logic for contracts
    private function validateContract(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,id',
            'project_id' => 'required|exists:projects,id',
            'subject' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
            'description' => 'required|string',
            'start_date' => 'required|date',
            'due_date' => 'required|date|after_or_equal:start_date',
        ]);
    }
}
