<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Exceptions\ImportRowException;
use App\Models\Corporate;
use App\Models\Plan;
use App\Services\ImportService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Modules\Internal\Services\CorporateService;

class PlanController extends Controller
{
    public function __construct(CorporateService $corporateService, ImportService $importService)
    {
        $this->corporateService = $corporateService;
        $this->importService = $importService;
    }
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        $plans = Plan::query()
            ->filter($request->all())
            ->where('corporate_id', $corporate_id)
            // ->whereHas('corporatePlan', function ($corporatePlan) use ($corporate_id) {
            //     $corporatePlan->where('corporate_id', $corporate_id);
            // })
            // ->with('corporatePlan')
            ->orderBy('corporate_plan_id', 'ASC')
            ->paginate()
            ->appends($request->all());

        return $plans;
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('internal::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('internal::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('internal::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public function planImport(Request $request, $corporate_id)
    {
        $request->validate([
            'file' => 'required|file|mimes:xls,xlsx,csv,txt',
        ]);
        $file_name = now()->getPreciseTimestamp(3) . '-' . $request->file('file')->getClientOriginalName();
        $file = $request->file('file')->storeAs('temp', $file_name);
        $corporate = Corporate::findOrFail($corporate_id);

        $import = $this->importService;
        $import->read(Storage::path('temp/' . $file_name));
        $import->write(Storage::disk('public')->path('temp/result-' . $file_name), 'xsls');

        $headers_map_to_table_fields = Plan::$doc_headers_to_field_map;

        // Write Header to File
        $result_headers = array_keys($headers_map_to_table_fields);
        array_push($result_headers, ['Ingest Code', 'Ingest Note']);
        $import->addArrayToRow($result_headers);

        $imported_plan_data = 0;
        $failed_plan_data = [];
        foreach ($import->reader->getSheetIterator() as $sheet) {
            $doc_headers_indexes = [];
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index == 1) { // First Row Must be Header
                    foreach ($row->getCells() as $index => $cell) {
                        $doc_headers_indexes[$index] = $cell->getValue();
                    }
                } else { // Next Row Should be Data
                    $plan_row = [];
                    foreach ($row->getCells() as $header_index => $cell) {
                        if (isset($headers_map_to_table_fields[$doc_headers_indexes[$header_index]]))
                            $plan_row[$headers_map_to_table_fields[$doc_headers_indexes[$header_index]]] = $cell->getValue();
                    }

                    // $imported_plan_data[] = $new_row; // Insert to Array
                    // Create Directly
                    try {
                        $rowResponse = $this->corporateService->handlePlanRow($corporate, $plan_row);

                        // Write Success Result to File
                        array_push($plan_row, 'SUCCESS');
                        $import->addArrayToRow($plan_row);
                        $imported_plan_data++;
                    } catch (ImportRowException $e) {
                        // Write Data Validation Error to File
                        array_push($plan_row, $e->getMessage());
                        $import->addArrayToRow($plan_row);
                        $failed_plan_data[] = ['row_number' => $index, 'error' => $e->getMessage()];
                    } catch (\Exception $e) {
                        // Write Server Error to File
                        array_push($plan_row, "Server Error");
                        $import->addArrayToRow($plan_row);
                        $failed_plan_data[] = ['row_number' => $index, 'error' => $e->getMessage()];
                    }
                }
            }

            break; //only read first sheet
        }
        $import->reader->close();
        Storage::delete('temp/' . $file_name);
        $import->writer->close();
        // throw(404);

        return [
            'total_successed_row' => $imported_plan_data,
            'total_failed_row' => count($failed_plan_data),
            'failed_row' => $failed_plan_data,
            'result_file' => [
                'url' => Storage::disk('public')->url('temp/result-' . $file_name),
                'name' => 'result-' . $file_name,
            ]
        ];
    }
}
