<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;

use App\Models\Invoice;
use App\Models\Project;
use App\Models\Tax;
use App\Models\Payment;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; 
use App\Models\Client;
use App\Models\Notification;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;

class ClientInvoiceController extends Controller
{
    // Show all invoices
    public function index()
    {
        // Get the authenticated user
        $user = Auth::user();

        // Ensure the user has a client ID
        if (!$user->client_id) {
            abort(403, 'Unauthorized action.');
        }

        // Filter invoices for the client's projects
        $invoices = Invoice::with('project', 'client')
            ->where('client_id', $user->client_id) // Filter by client_id
            ->get();

        $projects = Project::where('client_id', $user->client_id)->get(); // Only show the projects related to the client
        $clients = Client::where('id', $user->client_id)->get(); // The current client
        $taxes = Tax::all(); // Assuming a Tax table exists

        return view('client.invoice.index', compact('invoices', 'projects', 'clients', 'taxes'));
    }

    // Store a new invoice
    public function store(Request $request)
    {
        $request->validate([
            'project_id' => 'required|exists:projects,id',
            'client_id' => 'required|exists:clients,id',
            'project_price' => 'required|numeric',
            'discount' => 'nullable|numeric',
            'tax' => 'nullable|numeric',
            'issue_date' => 'required|date',
            'due_date' => 'required|date',
        ]);

        $invoice = new Invoice();
        $invoice->project_id = $request->input('project_id');
        $invoice->client_id = $request->input('client_id');
        $invoice->project_price = $request->input('project_price');
        $invoice->discount = $request->input('discount', 0);
        $invoice->tax = $request->input('tax', 0);
        $invoice->total_amount = $this->calculateTotal($invoice->project_price, $invoice->discount, $invoice->tax);
        $invoice->issue_date = $request->input('issue_date');
        $invoice->due_date = $request->input('due_date');
        $invoice->status = 'sent'; // Default status
        $invoice->save();

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

    // Update an invoice
    public function update(Request $request, Invoice $invoice)
    {
        // Similar validation and update logic
    }

    // Helper method to calculate the total amount
    private function calculateTotal($price, $discount, $tax)
    {
        $discountedPrice = $price - $discount;
        return $discountedPrice + ($discountedPrice * $tax / 100);
    }



    public function show($id)
    {
        $invoice = Invoice::with('payments', 'project', 'client')->findOrFail($id);
        $settings = Setting::first();
        return view('client.invoice.detail', compact('invoice', 'settings'));
    }

    public function pay(Request $request, $id)
    {
        $invoice = Invoice::findOrFail($id);
        
        $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'payment_method' => 'required|string',
            'transaction_id' => 'nullable|string',
            'payment_date' => 'required|date',
            'attachment' => 'nullable|file|max:2048',
        ]);

        $payment = new Payment();
        $payment->invoice_id = $invoice->id;
        $payment->amount = $request->amount;
        $payment->payment_method = $request->payment_method;
        $payment->transaction_id = $request->transaction_id;
        $payment->payment_date = $request->payment_date;

        if ($request->hasFile('attachment')) {
            // Delete the old image if it exists
            // Store the new image
            $image = $request->file('attachment');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('storage/img'), $imageName);
            $payment->attachment = $imageName;
        }

        $payment->save();

         // Create a new notification
         $notification = Notification::create([
            'title' => "A New Payment Request",
            'body' => 'Payment Amount:- '.$request->amount,
            'send_at' => now(), // Current date and time
            'sent' => $request->input('sent', false), // Default to false if not provided
            'url' => 'allpayments', // Example route for redirection
            'from_id' => Auth::id(), // Authenticated user's ID
            'to_id' => 0, // Client ID for to_id
        ]);


          // Check if email notifications for payment requests to admin are enabled
            $emailSettings = DB::table('email_notification_settings')->first(); // Assuming id=1 for admin settings

            // Fetch the admin's business email from settings
            $businessEmail = DB::table('settings')->value('business_email');

            // Send email if payment_request_mail_admin is set to 1
            if ($emailSettings && $emailSettings->payment_request_mail_admin == 1 && $businessEmail) {
                $data = [
                    'amount' => $request->amount,
                    'payment_method' => $request->payment_method,
                    'payment_date' => $request->payment_date,
                    'invoice_id' => $invoice->id,
                    'transaction_id' => $request->transaction_id,
                ];

                // Send email to admin
                Mail::send([], [], function ($message) use ($businessEmail, $data) {
                    $message->to($businessEmail)
                        ->subject('New Payment Request for Invoice: ' . $data['invoice_id'])
                        ->html("
                            <h1>New Payment Request</h1>
                            <p>A new payment has been requested with the following details:</p>
                            <ul>
                                <li><strong>Amount:</strong> {$data['amount']}</li>
                                <li><strong>Payment Method:</strong> {$data['payment_method']}</li>
                                <li><strong>Payment Date:</strong> {$data['payment_date']}</li>
                                <li><strong>Transaction ID:</strong> {$data['transaction_id']}</li>
                            </ul>
                            <p>Please login to view and confirm the payment details.</p>
                        ");
                });
            }

        return redirect()->route('clientinvoices.show', $invoice->id)->with('success', 'Payment details sent will be checked and confirmed.');
    }

    public function payment(Request $request)
    {
        // Get the status filter if provided (pending, approved, declined)
        $status = $request->input('status');
    
        // Get the authenticated client's ID
        $user = Auth::user();
        $clientId = $user->client_id;
    
        // Fetch payments
        $payments = Payment::when($status, function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->get() // First get all payments
            ->filter(function ($payment) use ($clientId) {
                // Filter payments based on matching client_id in the invoice table
                $invoice = Invoice::find($payment->invoice_id); // Fetch the associated invoice
                return $invoice && $invoice->client_id === $clientId; // Match the client_id
            });
    
        // Pass the filtered payments and status to the view
        return view('client.invoice.payments', compact('payments', 'status'));
    }
    
    

}
