<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Repair;
use App\Models\Asset;
use App\Models\AssetAssignment;   // ✅ use the correct model
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class RepairController extends Controller
{
    public function index()
    {
        $employees = \App\Models\Employee::with('department')->orderBy('name')->get();
        $repairs   = Repair::with('asset')->latest()->paginate(10);
        return view('asset.repairs.index', compact('repairs', 'employees'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'asset_id' => 'required|exists:assets,id',
            'issue'    => 'required|string|max:255',
            'invoice'  => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:2048',
        ]);

        $path = $request->hasFile('invoice')
            ? $request->file('invoice')->store('repairs', 'public')
            : null;

        Repair::create([
            'asset_id'     => $request->asset_id,
            'issue'        => $request->issue,
            'vendor_name'  => $request->vendor_name,
            'cost'         => $request->cost,
            'invoice_path' => $path,
            'sent_date'    => $request->sent_date,
            'status'       => 'In Repair',
        ]);

        // Optional: set asset status while in repair
        Asset::where('id', $request->asset_id)->update(['status' => 'Repair']);

        return back()->with('success', 'Repair record added successfully!');
    }

    public function markReturned($id)
    {
        $repair = Repair::findOrFail($id);
        $repair->update([
            'status'      => 'Returned',
            'return_date' => now(),
        ]);

        // Optional: set asset back In-Stock (or keep Assigned if you prefer a different flow)
        $repair->asset->update(['status' => 'In-Stock']);

        return back()->with('success', 'Asset marked as returned!');
    }

    public function destroy($id)
    {
        $repair = Repair::findOrFail($id);
        if ($repair->invoice_path) {
            Storage::disk('public')->delete($repair->invoice_path);
        }
        $repair->delete();
        return back()->with('success', 'Repair record deleted successfully!');
    }

    // ✅ AJAX: assets currently assigned to this employee
    public function assetsByEmployee($employeeId)
    {
        $assets = AssetAssignment::where('employee_id', $employeeId)
            ->whereNull('returned_date')
            ->with('asset:id,asset_tag,device_type')
            ->get()
            ->pluck('asset')
            ->filter()    // in case some relations are null
            ->values();

        return response()->json($assets);
    }

    public function viewInvoice($id)
    {
        $repair = Repair::findOrFail($id);

        if (!$repair->invoice_path || !Storage::disk('public')->exists($repair->invoice_path)) {
            abort(404, 'Invoice not found');
        }

        // Force inline display in browser
        $mime = Storage::disk('public')->mimeType($repair->invoice_path) ?? 'application/pdf';
        $filename = basename($repair->invoice_path);

        return new StreamedResponse(function () use ($repair) {
            echo Storage::disk('public')->get($repair->invoice_path);
        }, 200, [
            'Content-Type'        => $mime,
            'Content-Disposition' => 'inline; filename="'.$filename.'"',
            'Cache-Control'       => 'private, max-age=3600',
        ]);
    }

    public function downloadInvoice($id)
    {
        $repair = Repair::findOrFail($id);

        if (!$repair->invoice_path || !Storage::disk('public')->exists($repair->invoice_path)) {
            abort(404, 'Invoice not found');
        }

        $filename = 'invoice-'.($repair->asset->asset_tag ?? 'asset').'-'.$repair->id.'.'.pathinfo($repair->invoice_path, PATHINFO_EXTENSION);
        return Storage::disk('public')->download($repair->invoice_path, $filename);
    }

    public function history(Request $request)
{
    $request->validate([
        'asset_id'    => 'nullable|exists:assets,id',
        'employee_id' => 'nullable|exists:employees,id',
    ]);

    $q = \App\Models\Repair::with(['asset:id,asset_tag,device_type', 'employee:id,name'])
        ->orderBy('created_at', 'desc');

    if ($request->filled('asset_id'))    $q->where('asset_id', $request->asset_id);
    if ($request->filled('employee_id')) $q->where('employee_id', $request->employee_id);

    $repairs = $q->limit(100)->get()->map(function($r){
        return [
            'id'          => $r->id,
            'asset_tag'   => $r->asset->asset_tag ?? 'N/A',
            'device_type' => $r->asset->device_type ?? '-',
            'employee'    => $r->employee->name ?? '—',
            'issue'       => $r->issue,
            'vendor'      => $r->vendor_name,
            'cost'        => (float) $r->cost,
            'status'      => $r->status,
            'sent_date'   => optional($r->sent_date)->format('Y-m-d'),
            'return_date' => optional($r->return_date)->format('Y-m-d'),
            'created_at'  => $r->created_at->format('Y-m-d H:i'),
        ];
    });

    return response()->json($repairs);
}
// at the bottom of the class
public function historyByAsset($assetId)
{
    $repairs = \App\Models\Repair::where('asset_id', $assetId)
        ->orderByDesc('created_at')
        ->get(['id','issue','vendor_name','cost','status','sent_date','return_date','created_at']);

    return response()->json($repairs);
}


}
