<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\Client;
use App\Models\Project;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth; 

use Illuminate\Http\Request;

class ClientContractController extends Controller
{
    public function index()
    {
        // Get the authenticated user and their client_id
        $user = Auth::user();
        $user_id = $user->client_id;
    
        // Filter contracts by the authenticated user's client_id
        $contracts = Contract::with('client', 'project')
            ->where('client_id', $user_id)
            ->get();
        
        // Retrieve all clients, projects, and settings
        $clients = Client::all();
        $projects = Project::all();
        $setting = Setting::first();
        
        // Return the view with the filtered data
        return view('client.contracts.index', compact(
            'contracts', 
            'clients', 
            'projects', 
            'setting'
        ));
    }


    public function approve(Request $request)
    {
        $contract = Contract::find($request->contract_id);
        if ($contract) {
            $contract->status = 'Accepted';
            $contract->save();
            return response()->json(['message' => 'Contract approved successfully']);
        }
        return response()->json(['error' => 'Contract not found'], 404);
    }

    public function reject(Request $request)
    {
        // Validate that the rejection note is provided
        $request->validate([
            'contract_id' => 'required|exists:contracts,id',
            'rejection_note' => 'required|string|max:255',
        ]);
    
        $contract = Contract::find($request->contract_id);
        if ($contract) {
            // Save the rejection note and update the status
            $contract->status = 'Rejected';
            $contract->note = $request->rejection_note; // Assuming you have a 'rejection_note' column
            $contract->save();
    
            return response()->json(['message' => 'Contract rejected successfully']);
        }
    
        return response()->json(['error' => 'Contract not found'], 404);
    }
    

    
    
}
