<?php

namespace App\Http\Controllers\Asn;

use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use App\Services\Asn\AsnHistoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class AsnHistoryController extends Controller
{
    /**
     * The variable to hold AsnHistoryService class.
     * 
     * @var \App\Services\Asn\AsnHistoryService $asnHistoryService
     */
    protected $asnHistoryService;

    /**
     * Construtor function.
     * 
     * @param \App\Services\Asn\AsnHistoryService $asnHistoryService
     */
    public function __construct(AsnHistoryService $asnHistoryService)
    {
        $this->asnHistoryService = $asnHistoryService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('settings.asn-history.index');
    }

    /**
     * Display a listing of the resource.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getData(Request $request)
    {
        $asnHistory = $this->asnHistoryService->getAsnHistoryData();
        $asnHistory = $this->asnHistoryService->getFilteredData($asnHistory, $request);
        $asnHistory = $this->asnHistoryService->reIndexAsnData($asnHistory);
        $data = $this->asnHistoryService->getDataForDataTable($asnHistory, $request);

        return [
            "draw"            => intval($request->input('draw')),
            "recordsTotal"    => intval(count($asnHistory)),
            "recordsFiltered" => intval(count($asnHistory)),
            "data"            => $data,
        ];
    }

    /**
     * Downloads a file from the storage based on the given file path.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response The response containing the file download.
     */
    public function downloadFile(Request $request)
    {
        // Get file path from request.
        $file = $request->get('file_path');

        // Normalize file name to prevent directory traversal.
        $file = sanitizeDirectoryFilename($file);

        // Allowed file extensions.
        $allowedExtensions = ['xlsx', 'csv'];

        // Extract file extension and validate.
        $extension = getFileExtension($file);

        // Check if file has a valid extension
        if (!in_array($extension, $allowedExtensions, true)) {
            return redirect('/asn-history')->with('error', 'File type not allowed.');
        }

        // Define storage path (relative to storage/app/).
        $storagePath = storage_path($file);  // or your specific subdirectory.

        // Check if file exists using Storage facade.
        if (!File::exists($storagePath)) {
            return redirect('/asn-history')->with('error', 'File not found!');
        }

        return response()->download($storagePath);
    }

    /**
     * To sync the file based on supplier with the help of an artisan command.
     * 
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function reSyncFile(Request $request)
    {
        try {
            if (!Storage::disk('integration')->exists($request->get('file_path'))) {
                $result = [
                    'sync_status' => 'failed',
                    'message' => 'File not found!',
                ];
                return response()->json($result, 500);
            }
            Artisan::call($this->asnHistoryService->getResyncCommand($request));
            $result = [
                'sync_status' => 'success',
                'message' => 'Resynced successfully',
            ];
            return response()->json($result);
        } catch (\Throwable $th) {
            $result = [
                'sync_status' => 'failed',
                'message' => 'Some error occured while processing!. Maybe specific file sync method is not enabled for this supplier.',
                'actual_server_error' => $th->getMessage(),
            ];
            return response()->json($result, 500);
        }
    }
}
