<?php

namespace App\Http\Controllers\Leasing;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\UploadLeasingDataRequest;
use App\Models\LeasingDataUpload;
use App\Services\LeasingUploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    protected $uploadService;

    public function __construct(LeasingUploadService $uploadService)
    {
        $this->uploadService = $uploadService;
    }

    public function index()
    {
        $this->authorize('create', \App\Models\LeasingRecord::class);
        $profile = auth()->user()->leasingProfile;

        $uploads = $profile->uploads()->latest()->paginate(10);
        return view('leasing.uploads.index', compact('uploads'));
    }

    public function create()
    {
        $this->authorize('create', \App\Models\LeasingRecord::class);
        return view('leasing.uploads.create');
    }

    public function store(UploadLeasingDataRequest $request)
    {
        $this->authorize('create', \App\Models\LeasingRecord::class);
        $profile = auth()->user()->leasingProfile;
        $leasingProfileId = $profile->id;
        
        // Store in private storage for security
        $file = $request->file('file');
        $filename = $file->getClientOriginalName();
        $file->storeAs('private/uploads/leasing/' . $leasingProfileId, $filename);

        $upload = LeasingDataUpload::create([
            'leasing_profile_id' => $leasingProfileId,
            'filename' => $filename,
            'status' => 'pending',
            'row_count' => 0,
        ]);

        // Process immediately for small files (simulated for simplicity)
        $results = $this->uploadService->process($upload);

        return redirect()->route('leasing.uploads.show', $upload)
            ->with('success', "Proses upload selesai. Berhasil: {$results['valid']}, Gagal: {$results['invalid']}");
    }

    public function show(LeasingDataUpload $upload)
    {
        $profile = auth()->user()->leasingProfile;
        if ($upload->leasing_profile_id !== $profile->id) abort(403);
        
        $records = $upload->records()->paginate(20);
        return view('leasing.uploads.show', compact('upload', 'records'));
    }

    public function downloadTemplate()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="template_leasing_pro.csv"',
        ];

        $callback = function() {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['TGL', 'NOPOL', 'RANGKA', 'MESIN', 'MODEL', 'KENDARAAN', 'CAB', 'OVERDUE', 'SISA_SALDO', 'LEGAL_FLAG', 'MEMBER_WARNING', 'MEMBER_INSTRUCTION']);
            fputcsv($file, ['2024-01-25', 'B 1234 XYZ', 'MH1XXXXXXXX', 'JFKYYYYYY', 'NMAX 2023', 'YAMAHA', 'Jakarta Pusat', '30', '15000000', '0', 'STNK BLOKIR', 'HUBUNGI KANTOR TERDEKAT']);
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
