<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Carbon\Carbon;


class LanguageController extends Controller
{
    /**
     * Create a new language
     * POST /api/v1/languages
     */
    public function demo()
    {
        return response()->json([
            'success' => true,
            'message' => 'Language API is working'
        ]);
    }
    public function store(Request $request)
    {
        try {
            $id = DB::table('languages')->insertGetId([
                'code' => $request->input('code'),
                'name_en' => $request->input('name_en'),
                'name_native' => $request->input('name_native'),
                'is_active' => $request->boolean('is_active', true) ? 1 : 0,
                'is_default' => $request->boolean('is_default', false) ? 1 : 0,
                'status' => $request->input('status', 'active'),
                'created_at_utc' => Carbon::now('UTC')->toDateTimeString(),
                'updated_at_utc' => Carbon::now('UTC')->toDateTimeString(),
            ]);

            $language = DB::table('languages')->where('id', $id)->first();
            
            return response()->json([
                'success' => true,
                'message' => 'Language created successfully',
                'data' => $language
            ], 201);
            
        } catch (QueryException $e) {
            // Handle duplicate code (MySQL error 1062)
            if (isset($e->errorInfo[1]) && $e->errorInfo[1] === 1062) {
                return response()->json([
                    'success' => false,
                    'message' => 'Language code already exists'
                ], 409);
            }
            return response()->json([
                'success' => false,
                'message' => config('app.debug') ? $e->getMessage() : 'Database error'
            ], 500);
        }
    }

    /**
     * Activate language (set is_active=1)
     * PATCH /api/v1/languages/{id}/activate
     */
    public function activate(int $id)
    {
        $updated = DB::table('languages')
            ->where('id', $id)
            ->update(['is_active' => 1]);

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

        $language = DB::table('languages')->where('id', $id)->first();
        
        return response()->json([
            'success' => true,
            'message' => 'Language activated',
            'data' => $language
        ]);
    }

    /**
     * Deactivate language (set is_active=0)
     * PATCH /api/v1/languages/{id}/deactivate
     */
    public function deactivate(int $id)
    {
        $updated = DB::table('languages')
            ->where('id', $id)
            ->update(['is_active' => 0]);

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

        $language = DB::table('languages')->where('id', $id)->first();
        
        return response()->json([
            'success' => true,
            'message' => 'Language deactivated',
            'data' => $language
        ]);
    }

    /**
     * Optional: List all languages (for testing)
     * GET /api/v1/languages
     */
   public function index()
{
    $data = DB::table('languages')
        // 1. Select only the columns the frontend needs (Hide internal IDs/logs)
        ->select('id', 'code', 'name_en', 'name_native', 'is_default')
        
        // 2. Manually handle Soft Deletes (Your column is 'deleted_at_utc')
        ->whereNull('deleted_at_utc')
        
        // 3. Filter only Active languages
        ->where('is_active', 1)
        ->where('status', 'active')
        
        // 4. Order logically
        ->orderBy('name_en', 'asc')
        
        ->get();

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


    /**
     * Update an existing language
     * PUT /api/v1/languages/{id}
     */
    public function update(Request $request, int $id)
    {
        try {
            // 1. Check if language exists and is not soft-deleted
            $language = DB::table('languages')
                ->where('id', $id)
                ->whereNull('deleted_at_utc')
                ->first();

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

            // 2. Prepare update data
            $updateData = [
                'code' => $request->input('code', $language->code),
                'name_en' => $request->input('name_en', $language->name_en),
                'name_native' => $request->input('name_native', $language->name_native),
                'is_active' => $request->has('is_active') ? ($request->boolean('is_active') ? 1 : 0) : $language->is_active,
                'is_default' => $request->has('is_default') ? ($request->boolean('is_default') ? 1 : 0) : $language->is_default,
                'status' => $request->input('status', $language->status),
                'updated_at_utc' => Carbon::now('UTC')->toDateTimeString(),
                // 'updated_by' => auth()->id(), // Uncomment if you have authentication
            ];

            // 3. Perform update
            $updated = DB::table('languages')
                ->where('id', $id)
                ->update($updateData);

            // 4. Fetch updated record
            $updatedLanguage = DB::table('languages')
                ->where('id', $id)
                ->whereNull('deleted_at_utc')
                ->first();

            return response()->json([
                'success' => true,
                'message' => 'Language updated successfully',
                'data' => $updatedLanguage
            ]);

        } catch (QueryException $e) {
            // Handle duplicate code (MySQL error 1062)
            if (isset($e->errorInfo[1]) && $e->errorInfo[1] === 1062) {
                return response()->json([
                    'success' => false,
                    'message' => 'Language code already exists'
                ], 409);
            }

            return response()->json([
                'success' => false,
                'message' => config('app.debug') ? $e->getMessage() : 'Database error'
            ], 500);
        }
    }
}