<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\RationCardService;
use App\Services\RationCardImageService;
use App\Security\DecryptUtils;
use Illuminate\Http\Response as LaravelResponse;
use App\ResponseHandler\Response;
use Illuminate\Support\Facades\Log;



class RationCardController extends Controller
{
    protected $rationCardService;
    protected $rationCardImageService;
    protected $response;

    public function __construct(RationCardService $rationCardService, RationCardImageService $rationCardImageService, Response $response)
    {
        $this->rationCardService = $rationCardService;
        $this->rationCardImageService = $rationCardImageService;
        $this->response = $response;
    }

    // public function createRationCard(Request $request)
    // {
    //     $data = $request->all();
    //     return $this->rationCardService->createRationCard($data);
    // }
    public function createRationCard(Request $request)
    {
        try {
            $data = $request->getContent();

            if (empty($data)) {
                return $this->response->respondWithError('Request data is empty');
            }

            // Log the incoming data for debugging
            Log::info('Ration Card Creation - Raw data received:', [
                'content_length' => strlen($data),
                'first_50_chars' => substr($data, 0, 50)
            ]);

            $decryptedData = DecryptUtils::decryptRequestData($data);

            if ($decryptedData === null) {
                return $this->response->respondWithError('Failed to decrypt request data. Please check encryption format.');
            }

            if (!is_array($decryptedData)) {
                return $this->response->respondWithError('Invalid data type received: ' . gettype($decryptedData) . '. Expected array format.');
            }

            // Log successful decryption
            Log::info('Ration Card Creation - Data decrypted successfully:', [
                'keys' => array_keys($decryptedData)
            ]);

            return $this->rationCardService->createRationCard($decryptedData);
            
        } catch (\Exception $e) {
            Log::error('Ration Card Creation Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return $this->response->respondWithError('Failed to create ration card: ' . $e->getMessage());
        }
    }

    /**
     * Test endpoint for creating ration card without encryption (for debugging)
     */
    public function createRationCardTest(Request $request)
    {
        try {
            // Get data directly as JSON (no encryption)
            $data = $request->all();
            
            Log::info('Ration Card Test - Raw data:', $data);

            if (empty($data)) {
                return $this->response->respondWithError('Request data is empty');
            }

            return $this->rationCardService->createRationCard($data);
            
        } catch (\Exception $e) {
            Log::error('Ration Card Test Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return $this->response->respondWithError('Failed to create ration card: ' . $e->getMessage());
        }
    }

    /**
     * Create a ration card without voters
     * Endpoint for creating standalone ration cards
     */
    public function createRationCardOnly(Request $request)
    {
        $data = $request->getContent();

        if (empty($data)) {
            return $this->response->respondWithError('Request data is empty');
        }

        $decryptedData = DecryptUtils::decryptRequestData($data);

        if ($decryptedData == null || !is_array($decryptedData)) {
            return $this->response->respondWithError('Invalid or empty request data');
        }

        return $this->rationCardService->createRationCardOnly($decryptedData);
    }

    // Edit Ration Card
    public function editRationCard(Request $request, $id)
    {
        $data = $request->getContent();

        if (empty($data)) {
            return $this->response->respondWithError('Request data is empty');
        }

        $decryptedData = DecryptUtils::decryptRequestData($data);

        if ($decryptedData == null || !is_array($decryptedData)) {
            return $this->response->respondWithError('Invalid or empty request data');
        }

        // Validate if ration card exists
        $rationCard = $this->rationCardService->getRationCardById($id);
        if (!$rationCard) {
            return $this->response->respondWithError('Ration card not found');
        }

        // Proceed to update the ration card
        return $this->rationCardService->updateRationCard($id, $decryptedData);
    }

    /**
     * Edit ration card basic data only (without affecting voters)
     * 
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function editRationCardOnly(Request $request, $id)
    {
        $data = $request->getContent();

        if (empty($data)) {
            return $this->response->respondWithError('Request data is empty');
        }

        $decryptedData = DecryptUtils::decryptRequestData($data);

        if ($decryptedData == null || !is_array($decryptedData)) {
            return $this->response->respondWithError('Invalid or empty request data');
        }

        // Validate if ration card exists
        $rationCard = $this->rationCardService->getRationCardById($id);
        if (!$rationCard) {
            return $this->response->respondWithError('Ration card not found');
        }

        // Proceed to update only the ration card basic data
        return $this->rationCardService->updateRationCardOnly($id, $decryptedData);
    }

    // Get Ration Card Details
    public function getRationCard($id)
    {
        // Fetch ration card details by ID
        $rationCard = $this->rationCardService->getRationCardById($id);

        if (!$rationCard) {
            return $this->response->respondWithError('Ration card not found');
        }

        // Return ration card details
        // Return ration card details with a 200 status
        return response()->json([
            'status' => 200,
            'message' => 'Ration card details fetched successfully',
            'data' => $rationCard
        ], 200);
    }

    // In your RationCardController
    public function getRationCards(Request $request)
    {
        // Define how many items per page (default to 10)
        $perPage = $request->input('per_page', 10); // You can pass 'per_page' query parameter to control page size

        // Fetch paginated ration cards from service
        $rationCards = $this->rationCardService->getPaginatedRationCards($perPage);

        // Return paginated data as JSON response
        return response()->json([
            'status' => 200,
            'message' => 'Ration cards fetched successfully',
            'data' => $rationCards
        ], 200);
    }
    /**
     * Export ration cards as Excel - Optimized for large datasets
     * Handles 40k+ records efficiently with chunked processing
     */
    public function downloadAsExcel(Request $request)
    {
        try {
            // Extract filters from request
            $filters = [
                'boothNumber' => $request->input('boothNumber')
            ];

            return $this->rationCardService->downloadAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate Excel export: ' . $e->getMessage(),
                500
            );
        }

        // try {
        //     // ✅ Step 1: Get encrypted raw JSON
        //     $data = $request->getContent();

        //     if (empty($data)) {
        //         return $this->response->respondWithError('Request data is empty');
        //     }

        //     // ✅ Step 2: Decrypt
        //     $decryptedData = DecryptUtils::decryptRequestData($data);

        //     // ✅ Step 3: Convert to ARRAY (VERY IMPORTANT)
        //     $decryptedData = json_decode($decryptedData, true);

        //     if (!is_array($decryptedData)) {
        //         return $this->response->respondWithError('Invalid or empty request data');
        //     }

        //     // ✅ Step 4: Extract filters from decrypted data
        //     $filters = [
        //         'boothNumber' => $decryptedData['boothNumber'] ?? null
        //     ];

        //     // ✅ Step 5: Pass to service
        //     return $this->rationCardService->downloadAsExcel($filters);
        // } catch (\Exception $e) {
        //     return $this->response->respondWithError(
        //         'Failed to generate Excel export: ' . $e->getMessage(),
        //         500
        //     );
        // }
    }

    public function downloadVotersAsExcel(Request $request)
    {
        try {

   // ✅ Step 1: Get encrypted raw JSON
           // $data = $request->getContent();

            // if (empty($data)) {
            //     return $this->response->respondWithError('Request data is empty');
            // }

            // // ✅ Step 2: Decrypt
            // $decryptedData = DecryptUtils::decryptRequestData($data);

            // // ✅ Step 3: Convert to ARRAY (VERY IMPORTANT)
            // $decryptedData = json_decode($decryptedData, true);

            // if (!is_array($decryptedData)) {
            //     return $this->response->respondWithError('Invalid or empty request data');
            // }

            // Extract filters from request
            $filters = [
                'boothNumber' => $request['boothNumber'] ?? null,
                'gender' => $request['gender'] ?? null,
                'age_from' => $request['age_from'] ?? null,
                'age_until' => $request['age_until'] ?? null
            ];

            return $this->rationCardService->downloadVotersAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate Excel export: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Export ration cards as CSV - Faster for very large datasets
     * Recommended for 50k+ records
     */
    public function downloadAsCSV()
    {
        try {
            return $this->rationCardService->downloadAsCSV();
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate CSV export: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Export ration cards as Excel filtered by booth number
     * GET /api/ration-cards/export/excel/booth/{boothNumber}
     */
    public function downloadAsExcelByBooth($boothNumber)
    {
        try {
            // Convert booth number to filter format
            $filters = ['boothNumber' => $boothNumber];
            return $this->rationCardService->downloadAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate Excel export for booth ' . $boothNumber . ': ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Export voters as Excel filtered by booth number
     * GET /api/voters/export/excel/booth/{boothNumber}
     */
    public function downloadVotersAsExcelByBooth($boothNumber)
    {
        try {
            // Convert booth number to filter format
            $filters = ['boothNumber' => $boothNumber];
            return $this->rationCardService->downloadVotersAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate voters Excel export for booth ' . $boothNumber . ': ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Download ration cards by booth with voter counts (new endpoint)
     * POST /api/ration-cards/downloadRationCardsAsExcelByBooth/{boothNumber}
     */
    public function downloadRationCardsAsExcelByBooth($boothNumber)
    {
        try {
            return $this->rationCardService->downloadRationCardsAsExcelByBooth($boothNumber);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate ration cards Excel export for booth ' . $boothNumber . ': ' . $e->getMessage(),
                500
            );
        }
    }

   

    /**
     * Download unmapped voters by booth number as Excel
     * POST /api/excelOperation/downloadUnmappedVotersByBooth/{boothNumber}
     */
    public function downloadUnmappedVotersByBooth($boothNumber)
    {
        try {
            // Convert booth number to filter format
            $filters = ['boothNumber' => $boothNumber];
            return $this->rationCardService->downloadUnmappedVotersAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate unmapped voters Excel export for booth ' . $boothNumber . ': ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Download mapped voters by booth number as Excel
     * POST /api/excelOperation/downloadMappedVotersByBooth/{boothNumber}
     */
    public function downloadMappedVotersByBooth($boothNumber)
    {
        try {
            // Convert booth number to filter format
            $filters = ['boothNumber' => $boothNumber];
            return $this->rationCardService->downloadMappedVotersAsExcel($filters);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to generate mapped voters Excel export for booth ' . $boothNumber . ': ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Get ration card count for progress estimation
     */
    public function getRationCardCount()
    {
        try {
            $count = $this->rationCardService->getRationCardCount();
            return response()->json([
                'status' => 200,
                'message' => 'Ration card count fetched successfully',
                'data' => ['count' => $count]
            ], 200);
        } catch (\Exception $e) {
            return $this->response->respondWithError(
                'Failed to get ration card count: ' . $e->getMessage(),
                500
            );
        }
    }

    public function searchRationCardOrVoterId(Request $request)
    {
        // $value = $request->input('search'); // Assuming the value is sent in the body as 'value'
        // if (empty($value)) {
        //     return $this->response->respondWithError('Search value is required');
        // }

        // 1) Get RAW encrypted JSON input
        $data = $request->getContent();

        if (empty($data)) {
            return $this->response->respondWithError('Request data is empty');
        }

        // 2) Decrypt
        $decryptedData = DecryptUtils::decryptRequestData($data);
        // Now $decryptedData is a normal PHP array

        // 3) Extract the value
        $value = $decryptedData['search'] ?? null;

        if (empty($value)) {
            return $this->response->respondWithError('Search value is required');
        }

        // Check Ration Card first
        $rationCard = $this->rationCardService->getByRationCardNumber($value);
        if ($rationCard) {
            return $this->response->respondWithData('Ration card found.',  [
                'ration_card_id' => $rationCard->id,
                'voter_id_number' => null, // You can set this to null since it's not needed here
            ], new LaravelResponse);
        }

        // If not found in RationCard, check Voter ID
        $voter = $this->rationCardService->getByAnyValue($value);
        if ($voter) {
            return $this->response->respondWithData('Voter ID found.',  [
                'ration_card_id' => $voter->ration_card_id,
                'voter_id_number' => $voter->id,
            ], new LaravelResponse);
        }

        // If not found in either, return error
        return $this->response->respondWithError('Value not found in either Ration Card or Voter ID');
    }



    public function getRationCardAndVoterId(Request $request)
    {
        // 1) Get RAW encrypted JSON input
        $data = $request->getContent();

        if (empty($data)) {
            return $this->response->respondWithError('Request data is empty');
        }

        // 2) Decrypt
        $decryptedData = DecryptUtils::decryptRequestData($data);

        // 3) Extract the search value
        $value = $decryptedData['search'] ?? null;

        if (empty($value)) {
            return $this->response->respondWithError('Search value is required');
        }

        // Search by multiple criteria: ration card number, voter ID, phone number, or Aadhaar number
        $result = $this->rationCardService->searchByMultipleCriteria($value);

        if (!$result) {
            return $this->response->respondWithError('No record found for the provided search value');
        }

        return $this->response->respondWithData('Record found successfully', $result, new LaravelResponse);
    }

    
    // Delete Ration Card
    public function deleteRationCard(Request $request, $rationCardNumber)
    {
        // Validate if ration card exists
        $rationCard = $this->rationCardService->getByRationCardNumber($rationCardNumber);
        if (!$rationCard) {
            return $this->response->respondWithError('Ration card not found');
        }
        
        // Proceed to delete the ration card
        $deleted = $this->rationCardService->deleteRationCard($rationCardNumber);
        if ($deleted) {
            return $this->response->respondWithData('Ration card deleted successfully', null, new LaravelResponse);
        } else {
            return $this->response->respondWithError('Failed to delete ration card');
        }
    }

    /**
     * Generate ration card image
     * 
     * @param int $id Ration card ID
     * @return \Illuminate\Http\Response
     */
    public function generateCard($id)
    {
        try {
            // Generate the ration card image using HTML to Image
            $result = $this->rationCardImageService->generateRationCardImage($id);

            if (!$result['success']) {
                $statusCode = $result['error'] === 'Ration card not found' ? 404 : 500;
                return $this->response->respondWithError($result['error'], $statusCode);
            }

            // Read the generated image file
            $imageData = $this->rationCardImageService->readImageFile($result['imagePath']);

            if (!$imageData) {
                return $this->response->respondWithError('Failed to read generated image', 500);
            }

            // Return image as downloadable response
            return response($imageData)
                ->header('Content-Type', 'image/png')
                ->header('Content-Disposition', 'attachment; filename="' . $result['filename'] . '"');

        } catch (\Exception $e) {
            Log::error('Ration card image generation error: ' . $e->getMessage());
            return $this->response->respondWithError('Failed to generate ration card image: ' . $e->getMessage(), 500);
        }
    }
}
