<?php

namespace App\Http\Controllers\Mahasiswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\GetDataApiController;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

use App\Models\Proposal;
use App\Models\Kelompok;
use App\Models\Periode;
use App\Models\MonevInternal;
use App\Models\JadwalKegiatan;
use App\Models\BuktiAnggaran;
use App\Models\JenisSatuanBarang;

use Session;
use Alert;
use Auth;
use Illuminate\Support\Facades\Auth as FacadesAuth;

class MonevController extends Controller
{

    public function monev($id, Request $request)
    {
        $bio      = auth()->user()->rBiodata;
        $nim      = $bio->noidentitas;
        $periode  = Periode::query()->get();
        $year     = !is_null($request->year) ? $request->year : now()->year;
        $jadwal   = JadwalKegiatan::where('periode_id', $periode->where('status', '1')->first()->periode_id)
                                ->where('nama','Monev Internal '.$id)->first();
        // $jadwal = now();

        $title    = 'Monev Internal '.$id;
        $proposal = MonevInternal::with(['rProposal', 'rProposal.rPeriode', 'rJenisMonev', 'rNilaiMonevAll'])
                    ->whereHas('rProposal', function ($query) use($nim){
                        $query->whereHas('rKelompok', function ($query) use($nim){
                            $query->whereHas('rAnggota', function ($query) use($nim){
                                $query->where('nim', $nim);
                            });
                        });
                    })
                    ->whereHas('rJenisMonev', function ($query) use($id){
                        $query->where('nama', 'Monev Internal '.$id);
                    })
                    ->whereYear('created_at', $year)
                    ->orderBy('created_at')
                    ->get();

                    // dd($proposal);
        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'jadwal'    => $jadwal,
            'periode'   => $periode,
            'idmonev'   => $id,
            'year'      => $year,
        ];

        return view('backend.mahasiswa.monev.indexmonev'.$id, $data);
    }

    public function revisiMonevEd($id)
    {
        //
        $id = explode('__', decrypt($id));
        $proposal = Proposal::with(['rJenis'])->find($id[0]);

        if($id[1] == 'logbook'){ $title = 'Upload Logbook'; }
        elseif($id[1] == 'kemajuan'){ $title = 'Upload Laporan Kemajuan';}
        elseif($id[1] == 'produk'){ $title = 'Upload Video Produk Akhir';}
        elseif($id[1] == 'akhir'){ $title = 'Upload Laporan Akhir'; }
        elseif($id[2] == 'II'){ $title = 'Upload Revisi Proposal Monev II'; }
        else{$title = 'Upload Revisi Proposal Monev I';}

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'type'      => $id[1],
            'monev'     => $id[2],
        ];

        return view('backend.mahasiswa.monev.upload_monev', $data);
    }

    public function revisiMonev($id)
    {
        //
        $id = explode('__', decrypt($id));
        // $proposal = MonevInternal::with(['rProposal'])->find($id[0]);
        $proposal = MonevInternal::with(['rProposal'])->where('id', $id[0])->first();
        // dd($id);

        if($id[1] == 'logbook'){ $title = 'Upload Logbook'; }
        elseif($id[1] == 'kemajuan'){ $title = 'Upload Laporan Kemajuan';}
        elseif($id[1] == 'produk'){ $title = 'Upload Produk Akhir';}
        elseif($id[1] == 'akhir'){ $title = 'Upload Laporan Akhir'; }
        elseif($id[2] == 'II'){ $title = 'Upload Revisi Proposal Monev II'; }
        else{$title = 'Upload Revisi Proposal Monev I';}

        $label = '';
            if ($id[1] == 'logbook') {
                $label = 'Upload Logbook';
            } elseif ($id[1] == 'produk') {
                $label = 'Upload Video Produk Akhir';
            } elseif ($id[1] == 'kemajuan') {
                $label = 'Upload Laporan Kemajuan';
            } elseif ($id[1] == 'akhir') {
                $label = 'Upload Laporan Akhir';
            } elseif ($id[2] == 'II') {
                $label = 'Upload Revisi Proposal Monev II';
            } else {
                $label = 'Upload Revisi Proposal Monev I';
            }

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'type'      => $id[1],
            'monev'     => $id[2],
            'label'     => $label,
        ];

        return view('backend.mahasiswa.monev.upload_monev', $data);
    }

    public function uploadMonev(Request $request)
    {
        $pro   = $request->except('_token');

        $this->validate($request,
            [
                'file' => 'mimes:pdf|max:5000'
            ], [
                'file.required' => 'Tidak ada file yang di upload',
                'file.mimes' => 'File harus pdf',
                'file.max' => 'File tidak boleh lebih dari 5 mb',
            ]);

        $proposal = MonevInternal::with(['rProposal'])->find($pro['monev_id']);

        if ($pro['type'] !== 'produk') {
        $file_nama  = $proposal->rProposal->rPeriode->nama.'_'.$proposal->rProposal->proposal_id.'_'.now()->format('Y-m-d_H:i:s').'.'.$pro['file']->getClientOriginalExtension();

            if($pro['type'] == 'logbook'){
                $proposal->logbook_file   = $file_nama;
                $proposal->logbook_date   = now();
            }elseif($pro['type'] == 'kemajuan'){
                $proposal->kemajuan_file  = $file_nama;
                $proposal->kemajuan_date  = now();
            }elseif($pro['type'] == 'akhir'){
                $proposal->akhir_file     = $file_nama;
                $proposal->akhir_date     = now();
            }elseif($pro['type'] == 'proposal'){
                $proposal->upload_dokumen = $file_nama;
                $proposal->rProposal->upload_dokumen = $file_nama;
                $proposal->rProposal->updated_at = now();
                $proposal->rProposal->save();
                $proposal->date_upload    = now();
            }
        } else {
            $proposal->produk_url     = $request->produk_url;
            $proposal->produk_date    = now();
        }

        if ($pro['type'] == 'proposal') {
            Storage::disk('static')->put('simpmw/proposal/'.$proposal->rProposal->rPeriode->nama.'/'.$file_nama, file_get_contents($pro['file']->getRealPath()));
        } else {
            Storage::disk('static')->put('simpmw/monev/'.$pro['monev'].'/'.$pro['type'].'/'.$file_nama, file_get_contents($pro['file']->getRealPath()));
        }
        $proposal->save();

        return redirect()->route('mahasiswa.monev-index', $pro['monev'])->with('success', 'Proposal Berhasil revisi');
    }

    public function revisiMonevAll($id)
    {
        $id = explode('__', decrypt($id));
        // $proposal = MonevInternal::with(['rProposal'])->find($id[0]);
        $proposal = MonevInternal::with(['rProposal'])->where('id', $id[0])->first();

        $id[1] == 'II' ? $title = 'Revisi Dokumen Monev II' : $title = 'Revisi Dokumen Monev I';
        $type = ['proposal', 'logbook', 'kemajuan', 'akhir', 'produk'];
        $label = ['Unggah Revisi Proposal', 'Unggah Revisi Logbook', 'Unggah Revisi Laporan Kemajuan', 'Unggah Revisi Laporan Akhir', 'Unggah Revisi Produk Akhir'];

        $data = [
            'proposal'  => $proposal,
            'title'     => $title,
            'type'      => $type,
            'monev'     => $id[1],
            'label'     => $label,
        ];

        return view('backend.mahasiswa.monev.revisi_monev', $data);
    }

    public function uploadMonevRevisi(Request $request)
    {
        $pro   = $request->except('_token');
        $type = ['proposal', 'logbook', 'kemajuan', 'akhir', 'produk'];

        $request->validate([
            'produk_url' => 'nullable|url', // Produk URL validasi opsional
            'proposal' => 'nullable|mimes:pdf|max:5000',
            'logbook' => 'nullable|mimes:pdf|max:5000',
            'kemajuan' => 'nullable|mimes:pdf|max:5000',
            'akhir' => 'nullable|mimes:pdf|max:5000',
        ], [
            'mimes' => ':attribute harus berupa file PDF.',
            'max' => ':attribute tidak boleh lebih dari 5MB.',
            // 'produk_url.url' => 'Produk URL harus berupa URL valid.',
        ]);

        $proposal = MonevInternal::with(['rProposal'])->find($pro['monev_id']);

        foreach ($type as $field) {
            if ($field === 'produk' && isset($pro['produk_url'])) {
                $proposal->produk_url = $pro['produk_url'];
                $proposal->produk_date = now();
            } elseif (isset($pro[$field])) {
                $file = $pro[$field];
                $file_nama  = $proposal->rProposal->rPeriode->nama.'_'.$proposal->rProposal->proposal_id.'.'.$file->getClientOriginalExtension();
                $store = Storage::disk('static')->put('simpmw/monev/'.$pro['monev'].'/'.$field.'/'.$file_nama, file_get_contents($file->getRealPath()));
                $url = 'simpmw/monev/'.$pro['monev'].'/'.$field.'/'.$file_nama;

                $proposal->{$field . '_file'} = $file_nama;
                $proposal->{$field . '_date'} = now();
                $urls[] = $url;
            }
        }
        dd($pro, $urls, $store);

        $proposal->save();

        return redirect()->route('mahasiswa.monev-index', $pro['monev'])->with('success', 'Proposal Berhasil revisi');
    }

    public function buktiAnggaran($id)
    {
        $monev_id = decrypt($id);

        $title = 'Bukti Penggunaan Anggaran';

        $anggaran = BuktiAnggaran::with(['rProposal', 'rMonev'])
                    ->where('monev_id', $monev_id)
                    ->get();

        $monev = MonevInternal::with(['rProposal', 'rBuktiAnggaran' => function($query) {
                    $query->orderByRaw('CASE WHEN tgl_pembelian IS NULL THEN 0 ELSE 1 END ASC, tgl_pembelian ASC');
                }])
                ->where('id', $monev_id)
                ->first();

        $jenis_satuan = JenisSatuanBarang::select('jenis_satuan')
                        ->get();
        // dd($monev->rBuktiAnggaran);
        $data = [
            'title'         => $title,
            'anggaran'      => $anggaran,
            'monev'         => $monev,
            'jenis_satuan'  => $jenis_satuan
        ];

        return view('backend.mahasiswa.monev.anggaran.index', $data);
    }

    public function storeAnggaran(Request $request)
    {
        DB::beginTransaction();
        try {
            $key   = $request->except('_token');
            $userid = Auth::user()->id;

            $this->validate($request,
                [
                    'nota_file' => 'required|mimes:pdf|max:5000'
                ], [
                    'nota_file.required' => 'Tidak ada file yang di upload',
                    'nota_file.mimes' => 'File harus pdf',
                    'nota_file.max' => 'File tidak boleh lebih dari 5 mb',
                ]);

            $anggaran = MonevInternal::with(['rProposal', 'rBuktiAnggaran'])->find($key['monev_id']);

            $original_file = $key['nota_file']->getClientOriginalName();
            $file_nama  = $anggaran->rProposal->rPeriode->nama . '_Bukti-Anggaran_' . $anggaran->rProposal->proposal_id . '_' . pathinfo($original_file, PATHINFO_FILENAME) . '.' . $key['nota_file']->getClientOriginalExtension();

            Storage::disk('static')->put('simpmw/monev/II/bukti-anggaran/' . $file_nama, file_get_contents($key['nota_file']->getRealPath()));

            BuktiAnggaran::updateOrCreate([
                'id' => $key['id'],
            ],[
                'proposal_id' => $key['proposal_id'],
                'monev_id' => $key['monev_id'],
                'nama_kegiatan' => $key['nama_kegiatan'],
                'nama_barang' => $key['nama_barang'],
                'tgl_pembelian' => $key['tgl_pembelian'],
                'kuantitas' => $key['kuantitas'],
                'jenis_satuan' => $key['jenis_satuan'],
                'harga_satuan' => $key['harga_satuan'],
                'total_harga_per' => $key['kuantitas']*$key['harga_satuan'],
                'total_harga_seluruh' => null,
                'nota_file' => $file_nama,
                'created_by' => $userid,
                'updated_by' => $userid,
            ]);

            DB::commit();
            return redirect()->route('mahasiswa.monev-anggaran', ['id' => encrypt($key['monev_id'])])->with('success', 'Data berhasil disimpan');
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->route('mahasiswa.monev-anggaran', ['id' => encrypt($key['monev_id'])])->with('error', 'Gagal menyimpan data: ' . $e->getMessage());
        }
    }

    public function hapusAnggaran(Request $request)
    {
        $key   = $request->except('_token');
        $userid = Auth::user()->id;
        $id = decrypt($request->id);
        $anggaran = BuktiAnggaran::with(['rProposal', 'rMonev'])->find($id);

        if ($anggaran) {
            if ($anggaran->nota_file && Storage::disk('static')->exists('simpmw/monev/II/bukti-anggaran/' . $anggaran->nota_file)) {
                Storage::disk('static')->delete('simpmw/monev/II/bukti-anggaran/' . $anggaran->nota_file);
            }
            $anggaran->update([
                'deleted_at' => now(),
                'deleted_by' => $userid,
            ]);
            return response()->json(['status' => 'success', 'message' => 'Berhasil dihapus']);
        } else {
            return response()->json(['status' => 'error', 'message' => 'Proposal tidak ditemukan']);
        }
    }
}
