<?php

namespace App\Http\Controllers\Teknisi;

use App\Http\Controllers\Controller;
use App\Models\Production;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ReportController extends Controller
{
    public function productions(Request $request)
    {
        $query = Production::with([
            'order',
            'product',
            'productionMaterials.material',
            'productionSpareparts.sparepart',
        ])
        ->where('teknisi_id', Auth::id())
        ->orderBy('created_at', 'desc');

        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $productions = $query->paginate(20)->withQueryString();

        $totalProductions = (clone $query)->count();
        $totalMaterialCost = (clone $query)->sum('total_material_cost') ?? 0;
        $totalSparepartCost = (clone $query)->sum('total_sparepart_cost') ?? 0;
        $totalLaborCost = (clone $query)->sum('labor_cost') ?? 0;
        $totalProductionCost = $totalMaterialCost + $totalSparepartCost + $totalLaborCost;

        $chartData = Production::select(
                DB::raw('MONTH(created_at) as month'),
                DB::raw('YEAR(created_at) as year'),
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(total_production_cost) as total_cost'),
                DB::raw('SUM(labor_cost) as total_labor')
            )
            ->where('teknisi_id', Auth::id())
            ->where('created_at', '>=', Carbon::now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        return view('teknisi.reports.productions', compact(
            'productions',
            'totalProductions',
            'totalMaterialCost',
            'totalSparepartCost',
            'totalLaborCost',
            'totalProductionCost',
            'chartData'
        ));
    }

    public function showProduction(Production $production)
    {
        // Pastikan hanya teknisi yang ditugaskan yang bisa akses
        if (!$production->teknisi_id || (int)$production->teknisi_id !== (int)Auth::id()) {
            abort(403, 'Anda tidak memiliki akses ke laporan produksi ini.');
        }

        // Load semua relasi yang diperlukan
        $production->load([
            'order',
            'product.specifications',
            'product.images',
            'product.category',
            'teknisi',
            'supervisor',
            'completionApprover',
            'materialsReceiver',
            'sparepartsReceiver',
            'productionMaterials.material',
            'productionSpareparts.sparepart'
        ]);

        // Hitung total biaya
        $materialTotal = $production->total_material_cost ?? 0;
        $sparepartTotal = $production->total_sparepart_cost ?? 0;
        $laborTotal = $production->labor_cost ?? 0;
        $totalCost = $materialTotal + $sparepartTotal + $laborTotal;

        // Hitung durasi aktual dengan format yang mudah dipahami
        $actualDuration = null;
        $actualDurationFormatted = null;
        
        if ($production->actual_start_date && $production->completed_at) {
            $start = \Carbon\Carbon::parse($production->actual_start_date);
            $end = \Carbon\Carbon::parse($production->completed_at);
            $diff = $start->diff($end);
            
            $days = $diff->days;
            $hours = $diff->h;
            $minutes = $diff->i;
            
            // Format yang mudah dipahami
            $parts = [];
            if ($days > 0) {
                $parts[] = $days . ' hari';
            }
            if ($hours > 0) {
                $parts[] = $hours . ' jam';
            }
            if ($minutes > 0 && $days == 0) { // Hanya tampilkan menit jika kurang dari 1 hari
                $parts[] = $minutes . ' menit';
            }
            
            if (!empty($parts)) {
                $actualDurationFormatted = implode(' ', $parts);
            } else {
                $actualDurationFormatted = 'Kurang dari 1 menit';
            }
            
            // Untuk perbandingan dengan estimasi (dalam hari)
            $totalHours = $start->diffInHours($end);
            $actualDuration = round($totalHours / 24, 1);
            
        } elseif ($production->actual_start_date && $production->estimated_completion_date) {
            $start = \Carbon\Carbon::parse($production->actual_start_date);
            $end = \Carbon\Carbon::parse($production->estimated_completion_date);
            $diff = $start->diff($end);
            
            $days = $diff->days;
            $hours = $diff->h;
            $minutes = $diff->i;
            
            // Format yang mudah dipahami
            $parts = [];
            if ($days > 0) {
                $parts[] = $days . ' hari';
            }
            if ($hours > 0) {
                $parts[] = $hours . ' jam';
            }
            if ($minutes > 0 && $days == 0) {
                $parts[] = $minutes . ' menit';
            }
            
            if (!empty($parts)) {
                $actualDurationFormatted = implode(' ', $parts);
            } else {
                $actualDurationFormatted = 'Kurang dari 1 menit';
            }
            
            // Untuk perbandingan dengan estimasi (dalam hari)
            $totalHours = $start->diffInHours($end);
            $actualDuration = round($totalHours / 24, 1);
        }

        return view('teknisi.reports.production-detail', compact(
            'production', 
            'materialTotal', 
            'sparepartTotal', 
            'laborTotal', 
            'totalCost',
            'actualDuration',
            'actualDurationFormatted'
        ));
    }
}


