<?php

namespace App\Http\Controllers;

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

class InvoiceController extends Controller
{
    // Show all invoices
    public function index()
    {
        $invoices = Invoice::with('project', 'client')->get();
        $projects = Project::all();
        $clients = Client::all();
        $taxes = Tax::all(); // Assuming a Tax table exists

        return view('admin.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();


         // Find the client user and email notification settings
        $clientUser = DB::table('users')->where('client_id', $request->client_id)->first();
        $emailSettings = DB::table('email_notification_settings')->first();

        // Send email if new_invoices_mail_client is set to 1
        if ($emailSettings && $emailSettings->new_invoices_mail_client == 1) {
            if ($clientUser && $clientUser->email) {
                $data = [
                    'project_title' => DB::table('projects')->where('id', $request->project_id)->value('title'),
                    'invoice_number' => $invoice->id,
                    'project_price' => $invoice->project_price,
                    'discount' => $invoice->discount,
                    'tax' => $invoice->tax,
                    'total_amount' => $invoice->total_amount,
                    'issue_date' => $invoice->issue_date,
                    'due_date' => $invoice->due_date,
                    'client_name' => $clientUser->name,
                ];

                // Send email
                Mail::send([], [], function ($message) use ($clientUser, $data) {
                    $message->to($clientUser->email)
                        ->subject('New Invoice Created: ' . $data['project_title'])
                        ->html("
                            <h1>New Invoice Created</h1>
                            <p>Dear {$clientUser->name},</p>
                            <p>An invoice has been created for the project <strong>{$data['project_title']}</strong>.</p>
                            <ul>
                                <li><strong>Invoice Number:</strong> {$data['invoice_number']}</li>
                                <li><strong>Project Price:</strong> {$data['project_price']}</li>
                                <li><strong>Discount:</strong> {$data['discount']}</li>
                                <li><strong>Tax:</strong> {$data['tax']}</li>
                                <li><strong>Total Amount:</strong> {$data['total_amount']}</li>
                                <li><strong>Issue Date:</strong> {$data['issue_date']}</li>
                                <li><strong>Due Date:</strong> {$data['due_date']}</li>
                            </ul>
                            <p>Please login to view the full invoice details.</p>
                        ");
                });
            }
        }

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

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

    // Delete an invoice
    public function destroy(Invoice $invoice)
    {
        $invoice->delete();
        return redirect()->route('invoices.index')->with('success', 'Invoice deleted successfully.');
    }

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

    public function payment(Request $request)
    {
        // Get the status filter if provided (pending, approved, declined)
        $status = $request->input('status');

        // Fetch payments with optional filtering by status
        $payments = Payment::when($status, function ($query) use ($status) {
            return $query->where('status', $status);
        })->get();

        return view('admin.invoice.payments', compact('payments', 'status'));
    }


    public function approvePayment($id)
    {
        // Find the payment by its ID
        $payment = Payment::findOrFail($id);
        $payment->status = 'approved'; // Approve the payment
    
        // Retrieve the associated invoice through the payment's invoice relationship
        $invoice = $payment->invoice;
    
        // Update the total amount paid in the invoice
        $totalPaid = $invoice->total_pay_amount; // Sum all payments related to the invoice
        $invoice->total_pay_amount = $totalPaid + $payment->amount; // Set the total paid amount on the invoice
        $invoice->save(); // Save the updated invoice
    
        $payment->save(); // Save the approved payment
    
        // Redirect back to the all payments page with success message
        return redirect()->route('allpayments')->with('success', 'Payment approved successfully.');
    }
    

    public function declinePayment(Request $request, $id)
    {
        $payment = Payment::findOrFail($id);
        $payment->status = 'declined';
        $payment->note = $request->query('note');  // Save the decline reason (note)
        $payment->save();

        return redirect()->route('allpayments')->with('success', 'Payment declined with note.');
    }

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

}
