<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\PropService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomerPropertyServiceController extends Controller
{
    /**
     * Display a listing of the services assigned to the customer.
     */
    public function index(Customer $customer)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer belongs to the user's company
        if ($customer->unit && $customer->unit->property->CompanyID != $companyId) {
            abort(403, 'Unauthorized access to customer services.');
        }
        
        $customer->load('propServices');
        
        // Only show services that belong to the user's company
        $services = PropService::where('CompanyID', $companyId)->get();
        
        return view('customer-services.assign', [
            'customer' => $customer,
            'services' => $services,
            'assignedServices' => $customer->propServices->pluck('IDService')->toArray()
        ]);
    }
    /**
     * Show the form for assigning services to a customer.
     */
    public function create(Customer $customer)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer belongs to the user's company
        if ($customer->unit && $customer->unit->property->CompanyID != $companyId) {
            abort(403, 'Unauthorized access to customer services.');
        }
        
        // Only show services that belong to the user's company
        $services = PropService::where('CompanyID', $companyId)->get();
        $assignedServices = $customer->propServices->pluck('IDService')->toArray();
        
        return view('customer-services.assign', compact('customer', 'services', 'assignedServices'));
    }

    /**
     * Store a newly assigned service to the customer.
     */
    public function store(Request $request, Customer $customer)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer belongs to the user's company
        if ($customer->unit && $customer->unit->property->CompanyID != $companyId) {
            abort(403, 'Unauthorized access to customer services.');
        }

        // Check if customer has UnitID and is active
        if (!$customer->UnitID || $customer->AccountStatus !== 'A') {
            return back()
                ->with('sweet_alert', [
                    'icon' => 'error',
                    'title' => 'Cannot assign service',
                    'text' => 'Services can only be assigned to active customers with a unit assigned.',
                    'confirmButtonText' => 'Dismiss'
                ]);
        }

        $validated = $request->validate([
            'service_id' => [
                'required',
                'exists:PropService,IDService,CompanyID,' . $companyId
            ],
            'price' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:1',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'notes' => 'nullable|string',
        ]);

        // Check if the service is already assigned
        if ($customer->propServices()
            ->where('PropService.IDService', $validated['service_id'])
            ->exists()) {
            return back()->with('error', 'This service is already assigned to the customer.');
        }

        // Verify the service belongs to the user's company
        $service = PropService::where('IDService', $validated['service_id'])
            ->where('CompanyID', $companyId)
            ->firstOrFail();

        // Attach the service with additional data
        $customer->propServices()->attach($validated['service_id'], [
            'Price' => $validated['price'],
            'Quantity' => $validated['quantity'],
            'StartDate' => $validated['start_date'],
            'EndDate' => $validated['end_date'],
            'Notes' => $validated['notes'] ?? null,
            'IsActive' => true,
        ]);

        return redirect()->route('customers.services', $customer)
            ->with('success', 'Service assigned successfully.');
    }

    /**
     * Show the form for editing a service assignment.
     */
    public function edit(Customer $customer, PropService $service)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer and service belong to the user's company
        if (($customer->unit && $customer->unit->property->CompanyID != $companyId) || 
            $service->CompanyID != $companyId) {
            abort(403, 'Unauthorized access to edit this service assignment.');
        }

        // Verify the service is actually assigned to the customer
        if (!$customer->propServices()->where('PropService.IDService', $service->IDService)->exists()) {
            abort(404, 'Service assignment not found.');
        }

        // Get the pivot data for this service assignment
        $pivot = $customer->propServices()->where('PropService.IDService', $service->IDService)->first()->pivot;

        return view('customer-services.edit', compact('customer', 'service', 'pivot'));
    }

    /**
     * Update the specified service assignment.
     */
    public function update(Request $request, Customer $customer, PropService $service)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer and service belong to the user's company
        if (($customer->unit && $customer->unit->property->CompanyID != $companyId) || 
            $service->CompanyID != $companyId) {
            abort(403, 'Unauthorized access to update this service assignment.');
        }

        // Verify the service is actually assigned to the customer
        if (!$customer->propServices()->where('PropService.IDService', $service->IDService)->exists()) {
            abort(404, 'Service assignment not found.');
        }

        $validated = $request->validate([
            'quantity' => 'required|integer|min:1',
        ]);

        $customer->propServices()->updateExistingPivot($service->IDService, [
            'Quantity' => $validated['quantity'],
        ]);

        return back()->with('success', 'Service assignment updated successfully.');
    }

    /**
     * Remove the specified service assignment.
     */
    public function destroy(Customer $customer, PropService $service)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Verify the customer and service belong to the user's company
        if (($customer->unit && $customer->unit->property->CompanyID != $companyId) || 
            $service->CompanyID != $companyId) {
            abort(403, 'Unauthorized to remove this service assignment.');
        }

        // Verify the service is actually assigned to the customer
        if (!$customer->propServices()->where('PropService.IDService', $service->IDService)->exists()) {
            abort(404, 'Service assignment not found.');
        }

        $customer->propServices()->detach($service->IDService);
        
        return back()->with('success', 'Service assignment removed successfully.');
    }
}
