<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class DivisionController extends Controller
{
    public function index(Request $request)
    {
        $query = DB::table('divisions');

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%");
            });
        }

        if ($request->has('status') && $request->status !== '') {
            $query->where('active', $request->status === 'active');
        }

        $divisions = $query->orderBy('order')->get();

        return response()->json(['data' => $divisions]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'code' => 'required|string|max:10|unique:divisions,code',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'order' => 'required|integer',
            'active' => 'boolean'
        ]);

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

        $id = DB::table('divisions')->insertGetId([
            'code' => $request->code,
            'name' => $request->name,
            'description' => $request->description,
            'order' => $request->order,
            'active' => $request->active ?? true,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json(['success' => true, 'data' => DB::table('divisions')->find($id)], 201);
    }

    public function show(string $id)
    {
        $division = DB::table('divisions')->find($id);
        
        if (!$division) {
            return response()->json(['success' => false, 'message' => 'Division not found'], 404);
        }

        return response()->json(['data' => $division]);
    }

    public function update(Request $request, string $id)
    {
        $division = DB::table('divisions')->find($id);

        if (!$division) {
            return response()->json(['success' => false, 'message' => 'Division not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'code' => 'required|string|max:10|unique:divisions,code,' . $id,
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'order' => 'required|integer',
            'active' => 'boolean'
        ]);

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

        DB::table('divisions')->where('id', $id)->update([
            'code' => $request->code,
            'name' => $request->name,
            'description' => $request->description,
            'order' => $request->order,
            'active' => $request->active ?? true,
            'updated_at' => now()
        ]);

        return response()->json(['success' => true, 'data' => DB::table('divisions')->find($id)]);
    }

    public function destroy(string $id)
    {
        $division = DB::table('divisions')->find($id);

        if (!$division) {
            return response()->json(['success' => false, 'message' => 'Division not found'], 404);
        }

        DB::table('divisions')->where('id', $id)->delete();

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

    public function importCsv(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|mimes:csv,txt'
        ]);

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

        $file = $request->file('file');
        $handle = fopen($file->getRealPath(), 'r');
        
        $imported = 0;
        $failed = 0;
        $errors = [];

        // Skip header row
        fgetcsv($handle);

        while (($row = fgetcsv($handle)) !== false) {
            try {
                DB::table('divisions')->insert([
                    'code' => $row[0],
                    'name' => $row[1],
                    'description' => $row[2] ?? null,
                    'order' => $row[3] ?? 0,
                    'active' => true,
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                $imported++;
            } catch (\Exception $e) {
                $failed++;
                $errors[] = "Row {$row[0]}: " . $e->getMessage();
            }
        }

        fclose($handle);

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