<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Interfaces\DailyRepositoryInterface;
use App\Interfaces\LocationRepositoryInterface;
use App\Interfaces\ShiftRepositoryInterface;
use App\Interfaces\StatusRepositoryInterface;
use App\Interfaces\UnitRepositoryInterface;
use App\Models\Daily;
use App\Models\DetailDaily;
use App\Models\Location;
use App\Models\Shift;
use App\Models\Unit;
use Carbon\Carbon;
use Illuminate\Http\Request;
use PermissionHelper;
use Yajra\DataTables\Facades\DataTables;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use ZipArchive;

class MonthlyController extends Controller
{
    protected $shift;
    protected $unit;
    protected $status;
    protected $location;
    protected $daily;

    public function __construct(
        ShiftRepositoryInterface $shift,
        StatusRepositoryInterface $status,
        UnitRepositoryInterface $unit,
        LocationRepositoryInterface $location,
        DailyRepositoryInterface $daily,
    ) {
        $this->shift = $shift;
        $this->unit = $unit;
        $this->status = $status;
        $this->location = $location;
        $this->daily = $daily;
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $canCreate = PermissionHelper::hasPermission("daily-report")->create;
        $option = request()->option;
        $shift = $this->shift->all();
        $location = $this->location->all();
        $unit = $this->unit->all();

        $sitesId = request()->location_id;
        $shiftId = request()->shift_id;
        $date = request()->tanggal;


        $daily = $this->unit->datatableMonthly();
        if (request()->ajax()) {
            return $this->datatable($daily);
        }
        return view('monthly.index', compact('shift', 'unit', 'location', 'canCreate'));
    }


    public function generatePdf($untId, $month, $year, $shift)
    {
        $start = microtime(true); // mulai hitung waktu
        try {

            $allAccess = PermissionHelper::hasAllAccess();

            $shift = Shift::find($shift);
            $equipment = Unit::with([
                'daily' => function ($query) use ($shift) {
                    $query->where('shift_id', $shift->id);
                },
                'daily.detail.formItem',
                'unittype',
            ])
                ->when(!$allAccess, function ($rw) {
                    $rw->where("location_id", auth()->user()->location_id);
                })
                ->findOrFail($untId);

            $formItemsStatus = $this->extractFormItemsStatus($equipment, $month, $year);

            $pdf = PDF::loadView('monthly.monthly_report', [
                'formItemsStatus' => $formItemsStatus,
                'month' => $month,
                'year' => $year,
                'equipment' => $equipment,
                'shift' => $shift,
            ])
                ->setPaper('a3', 'landscape');

            $end = microtime(true); // waktu selesai
            $executionTime = $end - $start;
            logger("Waktu eksekusi generatePdf: {$executionTime} detik");

            return $pdf->stream('Monthly-Report-' . $equipment->code_unit . '.pdf', [
                'Content-Type' => 'application/pdf',
            ]);

        } catch (ModelNotFoundException $e) {

            return response()->json(['message' => 'Data laporan ini kosong atau tidak ada checklist'], 404);
        }
    }

    private function extractFormItemsStatus($equipment, $month, $year)
    {
        $formItemsStatus = [];

        foreach ($equipment->daily as $daily) {
            $reportDate = new \DateTime($daily->date);
            if ($reportDate->format('m') == $month && $reportDate->format('Y') == $year) {
                foreach ($daily->detail as $dailyItem) {
                    $day = $reportDate->format('d');
                    $formItemName = $dailyItem->formItem->name;
                    $status = $dailyItem->status->name;

                    $formItemsStatus[$formItemName][$day] = $status;
                }
            }
        }

        return $formItemsStatus;
    }

    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn("vehicle", function ($item) {
                return $item->unit_code . ' - ' . $item->serial_number_unit . " - " . ($item->unittype->name ?? "-");
            })
            ->addColumn("unit_code", function ($item) {
                return $item->unit_code ?? "-";
            })
            ->addColumn("jumlah_checklist", function ($item) {
                return count($item->daily) ?? "0";
            })

            ->addColumn("hours_meter", function ($item) {
                return $item->hours_meter ?? "0";
            })
            ->filterColumn('vehicle', function ($query, $keyword) {
                $query->where(function ($q) use ($keyword) {
                    $q->where('units.unit_code', 'like', "%{$keyword}%")
                        ->orWhere('units.serial_number_unit', 'like', "%{$keyword}%")
                        ->orWhereHas('unittype', fn($u) => $u->where('name', 'like', "%{$keyword}%"));
                });
            })
            ->orderColumn('vehicle', function ($query, $order) {
                $query->join('type_units', 'type_units.id', '=', 'units.type_id')
                    ->orderByRaw("CONCAT(units.unit_code, ' - ', units.serial_number_unit, ' - ', type_units.name) {$order}");
            })

            ->addColumn('action', function ($row) {
                $actionBtn = "<div class='d-flex gap-2'>";
                $actionBtn .= '<a href="javascript:void(0)"
                        data-id="' . $row->id . '"
                        class="print btn btn-info btn-sm"><i class="fa fa-print"></i></a>';
                $actionBtn .= "</div>";
                return $actionBtn;
            })
            ->rawColumns(['action', 'status_checklist'])
            ->make(true);
    }
}
