<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CustomerController extends Controller
{
    public function index()
    {
        $customers = Customer::withCount('sales')
            ->withSum(['sales as total_outstanding' => function ($q) {
                $q->where('outstanding_balance', '>', 0);
            }], 'outstanding_balance')
            ->latest()
            ->get()
            ->map(function ($customer) {
                return [
                    'id' => $customer->id,
                    'name' => $customer->name,
                    'email' => $customer->email,
                    'phone' => $customer->phone,
                    'address' => $customer->address,
                    'loyalty_points' => (int) ($customer->loyalty_points ?? 0),
                    'customer_balance' => (float) ($customer->customer_balance ?? 0),
                    'total_outstanding' => (float) ($customer->total_outstanding ?? 0),
                    'total_purchases' => (float) ($customer->total_purchases ?? 0),
                    'is_active' => $customer->is_active,
                    'sales_count' => $customer->sales_count,
                    'created_at' => $customer->created_at,
                    'updated_at' => $customer->updated_at,
                ];
            });

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

    public function store(Request $request)
    {
        $this->authorize('create-customers');

        $orgId = app('current_organization_id');

        $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => ['nullable', 'email', Rule::unique('customers', 'email')->where('organization_id', $orgId)],
                'phone' => 'nullable|string',
                'address' => 'nullable|string',
                'date_of_birth' => 'nullable|date',
                'is_active' => 'boolean',
            ]);

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

            return response()->json($customer, 201);
    }

    public function show(Customer $customer)
    {
        $customer->loadSum(['sales as total_outstanding' => function ($q) {
            $q->where('outstanding_balance', '>', 0);
        }], 'outstanding_balance');
        $data = $customer->load('sales')->toArray();
        $data['customer_balance'] = (float) ($customer->customer_balance ?? 0);
        $data['total_outstanding'] = (float) ($customer->total_outstanding ?? 0);
        return response()->json($data);
    }

    public function update(Request $request, Customer $customer)
    {
        $this->authorize('edit-customers');

        $orgId = app('current_organization_id');

        $validated = $request->validate([
            'name' => 'string|max:255',
            'email' => ['nullable', 'email', Rule::unique('customers', 'email')->where('organization_id', $orgId)->ignore($customer->id)],
            'phone' => 'nullable|string',
            'address' => 'nullable|string',
            'date_of_birth' => 'nullable|date',
            'is_active' => 'boolean',
        ]);

        $customer->update($validated);

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

    public function destroy(Customer $customer)
    {
        $this->authorize('delete-customers');

        $customer->delete();

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

    public function purchaseHistory(Customer $customer)
    {
        $sales = $customer->sales()
            ->with(['items.product', 'user'])
            ->latest()
            ->get();

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