<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Supplier;
use Illuminate\Support\Facades\DB;


class SupplierController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 10);
        $search = $request->get('search', '');

        $query = Supplier::query();

        if ($search) {
            $query->where('razon_social', 'like', "%{$search}%")
                  ->orWhere('ruc', 'like', "%{$search}%");
        }

        $suppliers = $query->orderBy('id', 'desc')->paginate($perPage);

        return response()->json([
            'success' => true,
            'suppliers' => $suppliers
        ]);
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'ruc'          => 'required|string|max:20|unique:suppliers,ruc',
            'razon_social' => 'required|string|max:255',
            'direccion'    => 'required|string|max:255',
            'departamento' => 'nullable|string|max:100',
            'provincia'    => 'nullable|string|max:100',
            'distrito'     => 'nullable|string|max:100',
            'estado'       => 'nullable|string|max:50',
            'condicion'    => 'nullable|string|max:50',
            'tipodocumento'=> 'nullable|string|max:50',
            'phone'        => 'nullable|string|max:20',
            'accounts'     => 'nullable|array',
            'accounts.*.account_number' => 'required|string|max:50',
            'accounts.*.bank_name'      => 'required|string|max:100',
            'accounts.*.status'         => 'required|in:0,1',
        ], [
            'ruc.required'          => 'El RUC es obligatorio.',
            'ruc.unique'            => 'El RUC ya está registrado.',
            'razon_social.required' => 'La razón social es obligatoria.',
            'direccion.required'    => 'La dirección es obligatoria.',
            'accounts.*.account_number.required' => 'El número de cuenta es obligatorio.',
            'accounts.*.bank_name.required' => 'El nombre del banco es obligatorio.',
        ]);

        DB::beginTransaction();
        try {
            $supplier = Supplier::create($validatedData);
            
            // Guardar cuentas bancarias si existen
            if (!empty($validatedData['accounts'])) {
                foreach ($validatedData['accounts'] as $account) {
                    $supplier->accounts()->create([
                        'account_number' => $account['account_number'],
                        'bank_name'      => $account['bank_name'],
                        'status'         => $account['status'],
                    ]);
                }
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Proveedor creado exitosamente',
                'data' => $supplier->load('accounts')
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Error al crear el proveedor',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $supplier = Supplier::findOrFail($id);

        $validatedData = $request->validate([
            'ruc'          => 'required|string|max:20|unique:suppliers,ruc,' . $supplier->id,
            'razon_social' => 'required|string|max:255',
            'direccion'    => 'required|string|max:255',
            'departamento' => 'nullable|string|max:100',
            'provincia'    => 'nullable|string|max:100',
            'distrito'     => 'nullable|string|max:100',
            'estado'       => 'nullable|string|max:50',
            'condicion'    => 'nullable|string|max:50',
            'tipodocumento'=> 'nullable|string|max:50',
            'phone'        => 'nullable|string|max:20',
            'accounts'     => 'nullable|array',
            'accounts.*.id'             => 'nullable|exists:accounts,id',
            'accounts.*.account_number' => 'required|string|max:50',
            'accounts.*.bank_name'      => 'required|string|max:100',
            'accounts.*.status'         => 'required|in:0,1',
        ], [
            'ruc.required'          => 'El RUC es obligatorio.',
            'ruc.unique'            => 'El RUC ya está registrado.',
            'razon_social.required' => 'La razón social es obligatoria.',
            'direccion.required'    => 'La dirección es obligatoria.',
        ]);

        DB::beginTransaction();
        try {
            $supplier->update($validatedData);

            // Sincronizar cuentas bancarias (versión simple: elimina todas y vuelve a crear)
            if (isset($validatedData['accounts'])) {
                // Elimina todas las cuentas anteriores del proveedor
                $supplier->accounts()->delete();

                // Crea todas las cuentas nuevas
                foreach ($validatedData['accounts'] as $accountData) {
                    $supplier->accounts()->create([
                        'account_number' => $accountData['account_number'],
                        'bank_name'      => $accountData['bank_name'],
                        'status'         => $accountData['status'],
                    ]);
                }
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Proveedor actualizado exitosamente',
               
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Error al actualizar el proveedor',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        $supplier = Supplier::findOrFail($id);
        $supplier->delete();

        return response()->json([
            'success' => true,
            'message' => 'Proveedor eliminado exitosamente'
        ]);
    }

    public function show($id)
    {
        $supplier = Supplier::with('accounts')->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $supplier
        ]);
    }
}
