<?php

namespace Modules\SystemCore\App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\SystemCore\App\Models\CoreCustomer;

class CustomerController extends Controller
{
    public function index()
    {
        return view('systemcore::customers.index');
    }

    public function indexAjax(Request $request)
    {
        $query = CoreCustomer::with(['paymentTerm', 'primaryAddress', 'primaryContact'])
            ->select('core_customers.*');

        // Search (DataTables sends search.value)
        if ($request->filled('search.value')) {
            $search = $request->input('search.value');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('customer_code', 'like', "%{$search}%");
            });
        }

        // Filter by type
        if ($request->filled('customer_type')) {
            $query->where('customer_type', $request->customer_type);
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        return datatables($query)
            ->addColumn('actions', function ($customer) {
                return view('components.datatable-actions', [
                    'id' => $customer->id,
                    'actions' => [
                        ['label' => __('View'), 'icon' => 'bx bx-show', 'url' => route('systemcore.customers.show', $customer->id)],
                        ['label' => __('Edit'), 'icon' => 'bx bx-edit', 'url' => route('systemcore.customers.edit', $customer->id)],
                        ['label' => __('Delete'), 'icon' => 'bx bx-trash', 'onclick' => "deleteCustomer({$customer->id})"],
                    ],
                ])->render();
            })
            ->editColumn('customer_type', fn ($customer) => $customer->customer_type->label())
            ->editColumn('status', fn ($customer) => "<span class='badge bg-{$customer->status->color()}'>{$customer->status->label()}</span>")
            ->editColumn('is_active', fn ($customer) => $customer->is_active ? '<span class="badge bg-success">'.__('Active').'</span>' : '<span class="badge bg-secondary">'.__('Inactive').'</span>')
            ->rawColumns(['status', 'is_active', 'actions'])
            ->make(true);
    }

    public function create()
    {
        return view('systemcore::customers.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'customer_type' => 'required|string',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'website' => 'nullable|url|max:255',
            'tax_id' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:100',
            'payment_term_id' => 'nullable|exists:core_payment_terms,id',
            'credit_limit' => 'nullable|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        $customer = CoreCustomer::create($validated);

        return redirect()->route('systemcore.customers.index')
            ->with('success', __('Customer created successfully'));
    }

    public function show(CoreCustomer $customer)
    {
        $customer->load([
            'paymentTerm',
            'addresses',
            'contacts',
            'documents',
            'salesOrders' => function ($query) {
                $query->orderBy('order_date', 'desc')->limit(10);
            },
        ]);

        // Calculate statistics
        $stats = [
            'total_orders' => $customer->salesOrders()->count(),
            'total_revenue' => $customer->salesOrders()->sum('total_amount'),
            'pending_orders' => $customer->salesOrders()->where('status', 'pending')->count(),
            'completed_orders' => $customer->salesOrders()->where('status', 'completed')->count(),
            'addresses_count' => $customer->addresses()->count(),
            'contacts_count' => $customer->contacts()->count(),
            'documents_count' => $customer->documents()->count(),
        ];

        return view('systemcore::customers.show', compact('customer', 'stats'));
    }

    public function edit(CoreCustomer $customer)
    {
        return view('systemcore::customers.edit', compact('customer'));
    }

    public function update(Request $request, CoreCustomer $customer)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'customer_type' => 'required|string',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'mobile' => 'nullable|string|max:50',
            'website' => 'nullable|url|max:255',
            'tax_id' => 'nullable|string|max:100',
            'vat_number' => 'nullable|string|max:100',
            'payment_term_id' => 'nullable|exists:core_payment_terms,id',
            'credit_limit' => 'nullable|numeric|min:0',
            'status' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        $customer->update($validated);

        return redirect()->route('systemcore.customers.index')
            ->with('success', __('Customer updated successfully'));
    }

    public function destroy(CoreCustomer $customer)
    {
        $customer->delete();

        return response()->json([
            'success' => true,
            'message' => __('Customer deleted successfully'),
        ]);
    }

    public function search(Request $request)
    {
        $search = $request->get('search', '');

        $customers = CoreCustomer::where('name', 'like', "%{$search}%")
            ->orWhere('email', 'like', "%{$search}%")
            ->orWhere('customer_code', 'like', "%{$search}%")
            ->limit(20)
            ->get(['id', 'customer_code', 'name', 'email', 'phone']);

        return response()->json($customers);
    }
}
