<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Client;
use App\Models\Location;
use App\Models\Account;
use App\Models\Person;
use App\Models\Organization;
use App\Models\Representative;
use App\Models\Province;  
use App\Models\Commune; 
use Illuminate\Support\Str;

class ClientController extends Controller
{
      public function index()
    {
       $clients = Client::with([
    'person.location',
    'organization.location',
    'organization.representatives',
    'account'
])->get();
        return response()->json($clients);
    }

// ClientController.php
public function search(Request $request)
{
    $query = $request->input('query', '');

    if (empty(trim($query))) {
        return response()->json([]);
    }

    $clients = Client::whereHas('person', function ($q) use ($query) {
        $q->where('first_name', 'like', "%{$query}%")
          ->orWhere('last_name', 'like', "%{$query}%");
    })
    ->with(['person.location', 'account'])
    ->get();

    // Add name + last_request_date to each result
    $clients->transform(function ($client) {
        $client->name = $client->person->first_name . ' ' . $client->person->last_name;
        //$client->last_request_date = optional($client->creditRequests()->latest()->first())->created_at;
        return $client;
    });

    return response()->json($clients);
}
public function store(Request $request)
    {
        DB::beginTransaction();

        try {
            // Common validation rules
            $commonRules = [
                'type' => 'required|in:person,organization',
                
               
                'location.colline' => 'required|string|max:100',
                'location.residence' => 'required|string|max:150',
                'account.accountNumber' => 'required|string|max:50',
                'account.branch' => 'required|string|max:100',
            ];

            // Person-specific rules
            $personRules = [
                'person.firstName' => 'required|string|max:100',
                'person.lastName' => 'required|string|max:100',
                'person.nationalId' => 'required|string|max:50',
                'person.birthDate' => 'required|date',
                'person.phone' => 'required|string|max:50',
                'person.category' => 'required|string|max:100',
            ];

            // Organization-specific rules
            $organizationRules = [
                'organization.companyName' => 'required|string|max:150',
                'organization.nif' => 'required|string|max:50',
                'organization.rc' => 'required|string|max:50',
                'organization.legalForm' => 'required|string|max:100',
                'organization.category' => 'required|string|max:100',
                'organization.representative.name' => 'required|string|max:100',
                'organization.representative.phone' => 'required|string|max:50',
            ];

            // Merge rules based on client type
            $rules = $commonRules;
            if ($request->type === 'person') {
                $rules = array_merge($rules, $personRules);
            } else {
                $rules = array_merge($rules, $organizationRules);
            }

            // Validate request
            $validator = Validator::make($request->all(), $rules);

            if ($validator->fails()) {
                return response()->json([
                    'errors' => $validator->errors()
                ], 422);
            }

            // Create client
            $client = Client::create([
                'type' => $request->type,
                'category' => $request->type === 'person' 
                    ? $request->person['category'] 
                    : $request->organization['category'],
            ]);

            // Create location
            $location = Location::create([
                'region' => $request->location['region'],
                'province' => $request->location['province'],
                'commune' => $request->location['commune'],
                'colline' => $request->location['colline'],
            ]);

            // Create account
            Account::create([
                'client_id' => $client->id,
                'account_number' => $request->account['accountNumber'],
                'branch' => $request->account['branch'],
            ]);

            // Create person or organization
            if ($request->type === 'person') {
                Person::create([
                    'client_id' => $client->id,
                    'location_id' => $location->id,
                    'first_name' => $request->person['firstName'],
                    'last_name' => $request->person['lastName'],
                    'birth_date' => $request->person['birthDate'],
                    'birth_place' => $request->person['birthPlace'] ?? null,
                    'residence' => $request->location['residence'],
                    'marital_status' => $request->person['maritalStatus'] ?? null,
                    'national_id' => $request->person['nationalId'],
                    'gender' => $request->person['gender'] ?? null,
                    'phone' => $request->person['phone'],
                    'children_count' => $request->person['childrenCount'] ?? 0,
                ]);
            } else {
                $org = Organization::create([
                    'client_id' => $client->id,
                    'location_id' => $location->id,
                    'company_name' => $request->organization['companyName'],
                    'nif' => $request->organization['nif'],
                    'rc' => $request->organization['rc'],
                    'creation_date' => $request->organization['creationDate'] ?? null,
                    'head_office' => $request->location['residence'],
                    'legal_form' => $request->organization['legalForm'],
                    'member_count' => $request->organization['members']['total'] ?? 0,
                    'women_count' => $request->organization['members']['women'] ?? 0,
                    'men_count' => $request->organization['members']['men'] ?? 0,
                    'youth_count' => $request->organization['members']['youth'] ?? 0,
                ]);

                Representative::create([
                    'organization_id' => $org->id,
                    'name' => $request->organization['representative']['name'],
                    'phone' => $request->organization['representative']['phone'],
                    'deputy_name' => $request->organization['representative']['deputy'] ?? null,
                ]);
            }

            DB::commit();

            return response()->json([
                'message' => 'Client created successfully',
                'client_id' => $client->id
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'error' => 'Server error: ' . $e->getMessage()
            ], 500);
        }
    }



    public function show($id)
    {
        $client = Client::with(['person.location', 'organization.representative', 'account'])->findOrFail($id);
        return response()->json($client);
    }
/*
public function store(Request $request)
{
    DB::beginTransaction();

    try {
        // -------------------------------
        // Validation rules
        // -------------------------------
        $commonRules = [
            'type' => 'required|in:person,organization',
            'location.colline'   => 'required|string|max:100',
            'location.residence' => 'required|string|max:150',
            'account.accountNumber' => 'required|string|max:50|unique:accounts,account_number',
            'account.branch'        => 'required|string|max:100',
        ];

        $personRules = [
            'person.firstName'  => 'required|string|max:100',
            'person.lastName'   => 'required|string|max:100',
            'person.nationalId' => 'required|string|max:50|unique:persons,national_id',
            'person.birthDate'  => 'required|date',
            'person.phone'      => 'required|string|max:50',
            'person.category'   => 'required|string|max:100',
        ];

        $organizationRules = [
            'organization.companyName'          => 'required|string|max:150',
            'organization.nif'                  => 'required|string|max:50|unique:organizations,nif',
            'organization.rc'                   => 'required|string|max:50|unique:organizations,rc',
            'organization.legalForm'            => 'required|string|max:100',
            'organization.category'             => 'required|string|max:100',
            'organization.representative.name'  => 'required|string|max:100',
            'organization.representative.phone' => 'required|string|max:50',
        ];

        $rules = $commonRules;
        if ($request->type === 'person') {
            $rules = array_merge($rules, $personRules);
        } else {
            $rules = array_merge($rules, $organizationRules);
        }

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }

        // -------------------------------
        // Create client
        // -------------------------------
        $client = Client::create([
            'type'     => $request->type,
            'category' => $request->type === 'person'
                ? $request->person['category']
                : $request->organization['category'],
        ]);

        // -------------------------------
        // Resolve Province & Commune
        // -------------------------------
        $provinceId   = $request->location['province_id'] ?? null;
        $provinceName = $request->location['province'] ?? null;

        if (!$provinceId && $provinceName) {
            $province = Province::firstOrCreate(
                ['name' => $provinceName],
                ['slug' => Str::slug($provinceName)]
            );
            $provinceId = $province->id;
        }

        $communeId   = $request->location['commune_id'] ?? null;
        $communeName = $request->location['commune'] ?? null;

        if (!$communeId && $communeName && $provinceId) {
            $commune = Commune::firstOrCreate(
                ['name' => $communeName, 'province_id' => $provinceId],
                ['slug' => Str::slug($communeName)]
            );
            $communeId = $commune->id;
        }

        // -------------------------------
        // Create location
        // -------------------------------
        $location = Location::create([
            'region'     => $request->location['region'],
            'province_id'=> $provinceId,
            'commune_id' => $communeId,
            'colline'    => $request->location['colline'],
            'residence'  => $request->location['residence'],
        ]);

        // -------------------------------
        // Create account
        // -------------------------------
        Account::create([
            'client_id'      => $client->id,
            'account_number' => $request->account['accountNumber'],
            'branch'         => $request->account['branch'],
        ]);

        // -------------------------------
        // Create person or organization
        // -------------------------------
        if ($request->type === 'person') {
            Person::create([
                'client_id'      => $client->id,
                'location_id'    => $location->id,
                'first_name'     => $request->person['firstName'],
                'last_name'      => $request->person['lastName'],
                'birth_date'     => $request->person['birthDate'],
                'birth_place'    => $request->person['birthPlace'] ?? null,
                'residence'      => $request->location['residence'],
                'marital_status' => $request->person['maritalStatus'] ?? null,
                'national_id'    => $request->person['nationalId'],
                'gender'         => $request->person['gender'] ?? null,
                'phone'          => $request->person['phone'],
                'children_count' => $request->person['childrenCount'] ?? 0,
            ]);
        } else {
            $org = Organization::create([
                'client_id'     => $client->id,
                'location_id'   => $location->id,
                'company_name'  => $request->organization['companyName'],
                'nif'           => $request->organization['nif'],
                'rc'            => $request->organization['rc'],
                'creation_date' => $request->organization['creationDate'] ?? null,
                'head_office'   => $request->location['residence'],
                'legal_form'    => $request->organization['legalForm'],
                'member_count'  => $request->organization['members']['total'] ?? 0,
                'women_count'   => $request->organization['members']['women'] ?? 0,
                'men_count'     => $request->organization['members']['men'] ?? 0,
                'youth_count'   => $request->organization['members']['youth'] ?? 0,
            ]);

            Representative::create([
                'organization_id' => $org->id,
                'name'            => $request->organization['representative']['name'],
                'phone'           => $request->organization['representative']['phone'],
                'deputy_name'     => $request->organization['representative']['deputy'] ?? null,
            ]);
        }

        DB::commit();

        return response()->json([
            'message'   => 'Client created successfully',
            'client_id' => $client->id
        ], 201);

    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json([
            'error' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
}
*/

    // PUT /clients/{id}
    public function update(Request $request, $id)
    {
        $client = Client::findOrFail($id);
        $client->update($request->only(['type', 'category']));
        // You can add updates for related models here if needed
        return response()->json(['message' => 'Client updated']);
    }

    // DELETE /clients/{id}
    public function destroy($id)
    {
        $client = Client::findOrFail($id);
        $client->delete();
        return response()->json(['message' => 'Client deleted']);
    }
}