<?php

namespace App\Http\Controllers;

use App\Models\MaintenanceDoc;
use App\Models\MaintenanceUnit;
use App\Models\MasterUnit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\View\View;

class MaintenanceUnitController extends Controller
{
    public function index(): view
    {
        $masterUnit  = MasterUnit::with('project')->where('status', 1)->paginate(5);
        
        return view('maintenance/unit_list', [
            'masterUnit'     => $masterUnit
        ]);
    }

    public function maintenanceList($unit_code)
    {
        $maintenanceList    = MaintenanceUnit::where('unit_code', $unit_code)->paginate(5);

        $unitData           = MasterUnit::where('unit_code', $unit_code)->select('unit_code', 'unit_name')->first()->toArray();

        return view('maintenance/maintenance_list', [
            'maintenanceList'   => $maintenanceList,
            'unitData'          => $unitData
        ]);
    }

    public function create($unit_code): view
    {
        $unitData           = MasterUnit::where('unit_code', $unit_code)->select('unit_code', 'unit_name')->first()->toArray();

        $currentStep        = MaintenanceUnit::where('unit_code', $unit_code)->orderBy('step', 'desc')->limit(1)->value('step') ?? 0;
        
        $newStep            = $currentStep + 1;

        $mnt_code           = 'MNT-'.$unit_code.'-'.str_pad($newStep, 3, '0', STR_PAD_LEFT);

        return view('maintenance/maintenance_form', [
            'unitData'          => $unitData,
            'mnt_code'          => $mnt_code,
            'newStep'           => $newStep
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'file_upload' => 'nullable|mimes:pdf|max:5000'
        ], [
            'file_upload.max' => 'Maksimal ukuran file 5 Mb'
        ]);

        DB::transaction(function () use ($request) {

            $step           = $request->step;
            $mnt_num        = 'MNT-' . date('YmdHis') . '-' . $step;
            $mnt_code       = $request->mnt_code;
            $mnt_date       = $request->mnt_date;
            $unit_code      = $request->unit_code;
            $description    = $request->mnt_description;
            $file_upload    = $request->file_upload;

            $getProject = MasterUnit::with('project')
                ->where('unit_code', $unit_code)
                ->firstOrFail();

            $unit_id        = $getProject->id;
            $project_id     = $getProject->project->id;
            $project_code   = $getProject->project->project_code;

            $maintenance = MaintenanceUnit::create([
                'project_id'    => $project_id,
                'project_code'  => $project_code,
                'mnt_num'       => $mnt_num,
                'mnt_code'      => $mnt_code,
                'step'          => $step,
                'mnt_date'      => $mnt_date,
                'unit_id'       => $unit_id,
                'unit_code'     => $unit_code,
                'description'   => $description
            ]);

            if ($file_upload) {
                $fileName       = Str::replace(' ', '_', $file_upload->getClientOriginalName());
                $fileMimeType   = $file_upload->getClientMimeType();
                $fileSizeBytes  = $file_upload->getSize();

                $folder         = 'maintenance_files/'.$unit_code;

                Storage::disk('public')->putFileAs(
                    $folder,
                    $file_upload,
                    $fileName
                );

                $path = Storage::disk('public')->path('maintenance_files');

                MaintenanceDoc::create([
                    'upl_num'       => 'UPL_DOC-' . date('YmdHis'),
                    'project_code'  => $project_code,
                    'project_id'    => $project_id,
                    'unit_code'     => $unit_code,
                    'unit_id'       => $unit_id,
                    'upl_ref_id'    => $maintenance->id,
                    'upl_ref_num'   => $maintenance->mnt_num,
                    'upl_ref_code'  => $maintenance->mnt_code,
                    'upl_date'      => now(),
                    'upl_type'      => 'MNT',
                    'upl_filename'  => $fileName,
                    'upl_filesize'  => $fileSizeBytes,
                    'upl_filetype'  => $fileMimeType,
                    'upl_filepath'  => $path
                ]);
            }
        });

        return redirect('/unit/maintenance_list/' . $request->unit_code);
    }

    public function show($mnt_code): view
    {
        $mntData    = MaintenanceUnit::with('unit')->where('mnt_code', $mnt_code)->firstOrFail();

        $getUploadedFile    = MaintenanceDoc::where('upl_ref_code', $mnt_code)->get();
        
        return view('maintenance/maintenance_detail',[
            'mntData'   => $mntData,
            'mntDocs'    => $getUploadedFile
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'file_upload' => 'nullable|mimes:pdf|max:5000'
        ], [
            'file_upload.max' => 'Maksimal ukuran file 5 Mb'
        ]);

        DB::transaction(function () use ($request) {

            $step           = $request->step;
            $mnt_num        = $request->mnt_num;
            $mnt_code       = $request->mnt_code;
            $mnt_date       = $request->mnt_date;
            $unit_code      = $request->unit_code;
            $description    = $request->mnt_description;
            $file_upload    = $request->file_upload;

            $getProject = MasterUnit::with('project')
                ->where('unit_code', $unit_code)
                ->firstOrFail();

            $unit_id        = $getProject->id;
            $project_id     = $getProject->project->id;
            $project_code   = $getProject->project->project_code;

            MaintenanceUnit::where('mnt_num', $mnt_num)->update([
                'mnt_date'      => $mnt_date,
                'description'   => $description
            ]);

            if ($file_upload) {
                $fileName       = Str::replace(' ', '_', $file_upload->getClientOriginalName());
                $fileMimeType   = $file_upload->getClientMimeType();
                $fileSizeBytes  = $file_upload->getSize();

               $folder         = 'maintenance_files/'.$unit_code;

                Storage::disk('public')->putFileAs(
                    $folder,
                    $file_upload,
                    $fileName
                );

                $path = Storage::disk('public')->path('maintenance_files');

                MaintenanceDoc::create([
                    'upl_num'       => 'UPL_DOC-' . date('YmdHis'),
                    'project_code'  => $project_code,
                    'project_id'    => $project_id,
                    'unit_code'     => $unit_code,
                    'unit_id'       => $unit_id,
                    'upl_ref_id'    => MaintenanceUnit::where('mnt_num', $mnt_num)->select('id')->value('id'),
                    'upl_ref_num'   => $mnt_num,
                    'upl_ref_code'  => $mnt_code,
                    'upl_date'      => now(),
                    'upl_type'      => 'MNT',
                    'upl_filename'  => $fileName,
                    'upl_filesize'  => $fileSizeBytes,
                    'upl_filetype'  => $fileMimeType,
                    'upl_filepath'  => $path
                ]);
            }
        });

        return redirect('/unit/maintenance_list/' . $request->unit_code);
    }

    public function destroyMnt($mnt_code)
    {
        // Simpan daftar file sebelum data dihapus
        $docs = MaintenanceDoc::where('upl_ref_code', $mnt_code)
            ->select('upl_num', 'upl_filename', 'unit_code')
            ->get();

        try {

            DB::transaction(function () use ($mnt_code) {

                MaintenanceDoc::where('upl_ref_code', $mnt_code)->delete();

                MaintenanceUnit::where('mnt_code', $mnt_code)->delete();

            });

            // Transaction berhasil, baru hapus file
            foreach ($docs as $doc) {

                Storage::disk('public')->delete(
                    'maintenance_files/' . $doc->unit_code . '/' . $doc->upl_filename
                );

            }

            return response()->json([
                'success' => true,
                'message' => 'Maintenance berhasil dihapus'
            ]);

        } catch (\Throwable $e) {

            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus maintenance.',
                'error'   => $e->getMessage()
            ], 500);

        }
    }
    
    public function destroyDoc($upl_num)
    {
        $getFiles    = MaintenanceDoc::where('upl_num', $upl_num)->select('upl_filename', 'unit_code')->first()->toArray();
        $upl_filename   = $getFiles['upl_filename'];
        $unit_code      = $getFiles['unit_code'];

        MaintenanceDoc::where('upl_num', $upl_num)->delete();
        Storage::disk('public')->delete('maintenance_files/' . $unit_code . '/' . $upl_filename);

        return response()->json([
            'success' => true,
            'message' => 'File ' .$upl_filename. ' berhasil dihapus'
        ]);
    }
}
