<?php

namespace App\Http\Controllers;

use App\Models\WorkRecord;
use App\Models\Expense;
use Illuminate\Http\Request;

class WorkRecordController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return WorkRecord::with(['equipment', 'expenses'])->latest()->get();
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'equipment_id' => 'required|exists:equipments,id',
            'operator_name' => 'nullable|string',
            'start_time' => 'nullable|date',
            'end_time' => 'nullable|date',
            'duration' => 'required|numeric',
            'duration_unit' => 'required|in:hour,day',
            'site' => 'nullable|string',
            'payment_type' => 'nullable|string',
            'operator_salary' => 'nullable|numeric',
            'voucher_date' => 'nullable|date',
            'expenses' => 'nullable|array',
            'expenses.*.type' => 'required|string',
            'expenses.*.amount' => 'required|numeric',
            'expenses.*.notes' => 'nullable|string',
        ]);

        $equipment = \App\Models\Equipment::findOrFail($validated['equipment_id']);
        $rate = ($validated['duration_unit'] === 'hour') ? $equipment->hourly_rate : $equipment->daily_rate;
        $base_cost = $validated['duration'] * $rate;
        
        $record = WorkRecord::create([
            'equipment_id' => $validated['equipment_id'],
            'operator_name' => $validated['operator_name'],
            'start_time' => $validated['start_time'],
            'end_time' => $validated['end_time'],
            'duration' => $validated['duration'],
            'duration_unit' => $validated['duration_unit'],
            'base_cost' => $base_cost,
            'total_expenses' => 0,
            'grand_total' => $base_cost,
            'site' => $validated['site'] ?? null,
            'payment_type' => $validated['payment_type'] ?? 'Cash',
            'operator_salary' => $validated['operator_salary'] ?? 0,
            'voucher_date' => $validated['voucher_date'] ?? date('Y-m-d'),
        ]);

        $total_expenses = 0;
        if (!empty($validated['expenses'])) {
            foreach ($validated['expenses'] as $expData) {
                $record->expenses()->create($expData);
                $total_expenses += $expData['amount'];
            }
        }

        $record->update([
            'total_expenses' => $total_expenses,
            'grand_total' => $base_cost + $total_expenses
        ]);

        return $record->load(['equipment', 'expenses']);
    }

    /**
     * Display the specified resource.
     */
    public function show(WorkRecord $workRecord)
    {
        return $workRecord->load(['equipment', 'expenses']);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, WorkRecord $workRecord)
    {
        $validated = $request->validate([
            'operator_name' => 'nullable|string',
            'duration' => 'numeric',
            'duration_unit' => 'in:hour,day',
            'status' => 'string'
        ]);

        $workRecord->update($validated);
        
        $equipment = $workRecord->equipment;
        $rate = ($workRecord->duration_unit === 'hour') ? $equipment->hourly_rate : $equipment->daily_rate;
        $base_cost = $workRecord->duration * $rate;
        $total_expenses = $workRecord->expenses()->sum('amount');

        $workRecord->update([
            'base_cost' => $base_cost,
            'total_expenses' => $total_expenses,
            'grand_total' => $base_cost + $total_expenses
        ]);

        return $workRecord->load(['equipment', 'expenses']);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(WorkRecord $workRecord)
    {
        $workRecord->delete();
        return response()->json(['success' => true]);
    }
}
