<?php

namespace App\Http\Controllers;

use App\Models\Alumno;
use App\Models\Documento;
use Illuminate\Http\Request;

class DocumentoController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'curp' => 'file|mimes:pdf,jpg,png',
            'acta' => 'file|mimes:pdf,jpg,png',
            'comprobante' => 'file|mimes:pdf,jpg,png',
        ]);

        $alumno = Alumno::findOrFail($request->alumno_id);

        $tipos = ['curp', 'acta', 'comprobante'];

        foreach ($tipos as $tipo) {
            if ($request->hasFile($tipo)) {
                $ruta = $request->file($tipo)->store('documentos', 'public');

                $alumno->documentos()->create([
                    'tipo' => $tipo,
                    'archivo' => $ruta
                ]);
            }
        }

        return back()->with('success', 'Documentos subidos correctamente');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

     public function ver($id)
    {
        $doc = Documento::findOrFail($id);

        if (
            !auth()->user()->hasRole('Alumno') &&
            !auth()->user()->hasRole('Promotor') &&
            !auth()->user()->hasRole('Control escolar')
        ) {
            abort(403);
        }

        return response()->file(storage_path('app/public/'.$doc->archivo));
    }
}
