<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Checkbook;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class CheckbookController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            // Créer les tables si elles n'existent pas
            $this->ensureTablesExist();
            
            $query = Checkbook::withCount(['checks as used_checks_count' => function ($query) {
                $query->where('status', 'used');
            }, 'checks as unused_checks_count' => function ($query) {
                $query->where('status', 'unused');
            }]);

            if ($request->has('status')) {
                $query->where('status', $request->get('status'));
            }

            $checkbooks = $query->orderBy('created_at', 'desc')
                               ->paginate($request->get('per_page', 15));
            
            return response()->json($checkbooks);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Erreur lors du chargement'], 500);
        }
    }
    
    private function ensureTablesExist()
    {
        \DB::statement("CREATE TABLE IF NOT EXISTS checkbooks (
            id SERIAL PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            bank_name VARCHAR(255) NOT NULL,
            account_number VARCHAR(255) NOT NULL,
            start_number VARCHAR(20) NOT NULL,
            end_number VARCHAR(20) NOT NULL,
            total_checks INTEGER NOT NULL,
            status VARCHAR(20) DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");

        \DB::statement("CREATE TABLE IF NOT EXISTS checks (
            id SERIAL PRIMARY KEY,
            checkbook_id INTEGER NOT NULL REFERENCES checkbooks(id) ON DELETE CASCADE,
            check_number VARCHAR(20) NOT NULL,
            status VARCHAR(20) DEFAULT 'unused',
            amount DECIMAL(15,2),
            payee VARCHAR(255),
            issue_date DATE,
            cash_date DATE,
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(checkbook_id, check_number)
        )");
    }

    public function store(Request $request): JsonResponse
    {
        try {
            $this->ensureTablesExist();
            
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'bank_name' => 'required|string|max:255',
                'account_number' => 'required|string|max:255',
                'start_number' => 'required|string|max:20',
                'end_number' => 'required|string|max:20',
            ]);

            $startNumber = (int) $validated['start_number'];
            $endNumber = (int) $validated['end_number'];

            if ($endNumber <= $startNumber) {
                return response()->json(['error' => 'Le numéro de fin doit être supérieur au numéro de début'], 422);
            }

            $validated['total_checks'] = $endNumber - $startNumber + 1;

            $checkbook = Checkbook::create($validated);
            $checkbook->generateChecks();

            return response()->json($checkbook, 201);
        } catch (\Exception $e) {
            \Log::error('Erreur création carnet: ' . $e->getMessage());
            return response()->json(['error' => 'Erreur lors de la création du carnet'], 500);
        }
    }

    public function show(Checkbook $checkbook): JsonResponse
    {
        return response()->json($checkbook->load('checks'));
    }

    public function update(Request $request, Checkbook $checkbook): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'string|max:255',
            'bank_name' => 'string|max:255',
            'account_number' => 'string|max:255',
            'status' => 'in:active,completed,cancelled',
        ]);

        $checkbook->update($validated);
        return response()->json($checkbook->load('checks'));
    }

    public function destroy(Checkbook $checkbook): JsonResponse
    {
        $checkbook->delete();
        return response()->json(['message' => 'Carnet de chèques supprimé avec succès']);
    }
}