<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Scrap;
use App\Models\Asset;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ScrapController extends Controller
{
    public function index()
    {
        // Assets available to scrap: everything NOT already scrapped
        // (and optionally not in repair). Adjust as per your statuses.
        $assetsAvailable = Asset::where('status', '!=', 'Scrapped')
            ->orderBy('asset_tag')
            ->get(['id','asset_tag','device_type']);

        $scraps = Scrap::with('asset')->latest()->paginate(10);

        return view('asset.scraps.index', compact('assetsAvailable', 'scraps'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'asset_id' => 'required|exists:assets,id',
            'reason'   => 'nullable|string|max:255',
            'vendor'   => 'nullable|string|max:255',
            'scrap_date' => 'nullable|date',
            'certificate' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:4096',
        ]);

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

        $scrap = Scrap::create([
            'asset_id'        => $request->asset_id,
            'reason'          => $request->reason,
            'vendor'          => $request->vendor,
            'scrap_date'      => $request->scrap_date,
            'certificate_path'=> $path,
            'status'          => 'Scrapped',
        ]);

        // Mark asset as Scrapped
        Asset::where('id', $request->asset_id)->update(['status' => 'Scrap']);

        return back()->with('success', 'Asset scrapped successfully.');
    }

    public function restore($id)
    {
        $scrap = Scrap::with('asset')->findOrFail($id);

        // Mark record as restored
        $scrap->update(['status' => 'Restored']);

        // Restore asset status (you can choose "In-Stock" or "Working")
        $scrap->asset?->update(['status' => 'In-Stock']);

        return back()->with('success', 'Asset restored from scrap.');
    }

    public function destroy($id)
    {
        $scrap = Scrap::findOrFail($id);

        if ($scrap->certificate_path) {
            Storage::disk('public')->delete($scrap->certificate_path);
        }

        $scrap->delete();
        return back()->with('success', 'Scrap record deleted.');
    }

    public function viewCertificate($id)
    {
        $scrap = Scrap::findOrFail($id);

        if (!$scrap->certificate_path || !Storage::disk('public')->exists($scrap->certificate_path)) {
            abort(404, 'Certificate not found');
        }

        $mime = Storage::disk('public')->mimeType($scrap->certificate_path) ?? 'application/pdf';
        $filename = basename($scrap->certificate_path);

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

    public function downloadCertificate($id)
    {
        $scrap = Scrap::findOrFail($id);

        if (!$scrap->certificate_path || !Storage::disk('public')->exists($scrap->certificate_path)) {
            abort(404, 'Certificate not found');
        }

        $original = basename($scrap->certificate_path);
        return Storage::disk('public')->download($scrap->certificate_path, $original);
    }
}
