<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Master\FormKriteria;
use App\Models\Master\Provinsi;
use App\Models\Master\Kabupaten;
use App\Models\Master\Kecamatan;
use App\Models\Master\Sekolah;
use App\Models\Penilaian;
use App\Models\Kuesioner;
use App\Models\User;
use Hash;

class AjaxController extends Controller
{
    function authApi() {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://10.50.50.74/api/login',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{
                "email" : "ilhamwara@gmail.com",
                "password": "@Dinaslhdki123"
            }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }
    function sendEmail($to,$subject,$name,$kode,$token) {
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://10.50.50.74/api/email/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{
                "ApiKey" : "sk-25e88e0dfa73013ff5529d6c5e00462b",
                "To" : "'.$to.'",
                "Subject" : "'.$subject.'",
                "Html": "<!DOCTYPE html><html lang=\'id\'><head><meta charset=\'UTF-8\' /><meta name=\'viewport\' content=\'width=device-width, initial-scale=1.0\' /><title>SIDIA Jakarta</title><style>body{background-color:#f6f7fb;margin:0;padding:0;font-family:Arial,sans-serif;color:#333}.container{max-width:600px;margin:40px auto;background-color:#fff;border:1px solid #e5e5e5;border-radius:8px;overflow:hidden}.header{text-align:center;padding:30px 20px 10px 20px;border-bottom:1px solid #eee}.header img{width:90px;height:auto}.app-name{font-weight:bold;font-size:20px;margin-top:8px;color:#222}.body{padding:30px 40px}.body p{line-height:1.6;font-size:15px;margin:0 0 15px 0}.code-box{background-color:#f3f3f3;text-align:center;font-size:32px;font-weight:bold;padding:15px 0;border-radius:5px;letter-spacing:2px;margin:20px 0}.footer{font-size:13px;color:#888;text-align:center;padding:15px 20px 25px 20px;background-color:#fafafa;border-top:1px solid #eee}a{color:#0078d7;text-decoration:none}</style></head><body><div class=\'container\'><div class=\'header\'><img src=\'https://adiwiyata.dinaslhdki.id/assets/logo-dinas.ico\' alt=\'SIDIA Jakarta Logo\'/><div class=\'app-name\'>SIDIA Jakarta</div></div><div class=\'body\'><p>Hai <b>'.@$name.'</b>,</p><p>Gunakan kode di bawah ini untuk mereset kata sandi akun Anda.</p><div class=\'code-box\'>'.$kode.'</div><p>Kode ini akan kedaluwarsa dalam <b>15 menit</b>.</p><p>Tidak meminta reset kata sandi ini? Abaikan email ini atau <a href=\''.url('/#helpdesk').'\'>hubungi kami</a>.</p></div><div class=\'footer\'>&copy; '.date('Y').' SIDIA Jakarta. Semua hak dilindungi.</div></div></body></html>"
            }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: '.$token
            ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
    }
    function sendCode(Request $request) {
        // $request->validate(['email' => 'required|email']);
        if(@$request->email){

            if(@$request->password){
                $user = User::where('email', $request->email)->where('code_change_password', $request->kode)->first();
                $user->password = Hash::make($request->password);
                $user->save();

                return response()->json(['status' => true,'code' => false,'password' => false,'redirect' => true]);

            }elseif(@$request->kode){
                $user = User::where('code_change_password', $request->kode)->first();
                if(@$user){
                    return response()->json(['status' => true,'code' => false,'password' => true]);
                }else{
                    return response()->json(['status' => false,'message' => 'Kode Tidak Valid']);
                }
            }else{
                $user = User::where('email', $request->email)->first();
                // dd();
                if(@$user){
                    $response = json_decode($this->authApi());
                    // dd();

                    $user->code_change_password = \Str::random(5);
                    $user->save();

                    //send email
                    $this->sendEmail($user->email,'Lupa Password',$user->name,$user->code_change_password,$response->data->token);
                    
                    return response()->json(['status' => true,'code' => true,'password' => false]);
                }else{
                    return response()->json(['status' => false,'message' => 'Email Tidak Valid']);
                }
            }

            
            
        }
    }
    
    function checkEmail(Request $request){
        $request->validate(['email' => 'required|email']);

        $exists = User::where('email', $request->email)->exists();

        return response()->json(['exists' => $exists]);
    }
    public function uploadTemp(Request $request)
    {
        $request->validate([
            'file.*' => 'required|file|mimes:pdf|max:100000',
        ]);

        $uploadedFiles = [];

        if ($request->hasFile('file')) {
            foreach ($request->file('file') as $file) {
                $filename = uniqid() . '-' . time() . '.' . $file->getClientOriginalExtension();
                $path = $file->storeAs('tmp_uploads', $filename);

                $uploadedFiles[] = [
                    'filename' => $filename,
                    'url' => asset('storage/tmp_uploads/' . $filename),
                ];
            }

            return response()->json([
                'success' => true,
                'files' => $uploadedFiles, // Kembalikan semua file
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Upload failed.',
        ]);
    }
    public function uploadTempImage(Request $request)
    {
        $request->validate([
            'file.*' => 'required|file|mimes:png,jpg,jpeg|max:100000',
        ]);

        $uploadedFiles = [];

        if ($request->hasFile('file')) {
            foreach ($request->file('file') as $file) {
                $filename = uniqid() . '-' . time() . '.' . $file->getClientOriginalExtension();
                $path = $file->storeAs('tmp_uploads', $filename);

                $uploadedFiles[] = [
                    'filename' => $filename,
                    'url' => asset('storage/tmp_uploads/' . $filename),
                ];
            }

            return response()->json([
                'success' => true,
                'files' => $uploadedFiles, // Kembalikan semua file
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Upload failed.',
        ]);
    }
    public function sekolahNpsn(Request $request)
    {
        // dd($request->all());
        // if ($request->ajax()) {
            $query = $request->get('query');
            if(@$request->get('tingkat_sekolah')){
                $data = Sekolah::where('ms_tingkat_sekolah_id',$request->get('tingkat_sekolah'))->where('npsn', 'LIKE', "%{$query}%")->orderBy('npsn','ASC')->limit(20)->get(); 
            }else{
                $data = Sekolah::where('npsn', 'LIKE', "%{$query}%")->orderBy('npsn','ASC')->limit(20)->get(); 
            }
            // Sesuaikan dengan model & kolom yang diinginkan
            // dd($data);

            return response()->json($data);
        // }
    }
    public function getSekolahSK(Request $request)
    {
        $kuesioner = Kuesioner::where('level',($request->data-1))->where('tahun',date('Y'))->where('status',10)->get();
        $data = [];
        foreach ($kuesioner as $key => $value) {
            $data[$key]['id'] = encode_id($value->ms_sekolah_id);
            $data[$key]['name'] = $value->sekolah->nama_sekolah;
        }
        
        return response()->json($data);
    }
    public function getSekolahUsulan(Request $request)
    {
        $kuesioner = Kuesioner::where('level',($request->data-1))->where('tahun',date('Y'))->where('status',0)->get();
        $data = [];
        foreach ($kuesioner as $key => $value) {
            $data[$key]['id'] = encode_id($value->ms_sekolah_id);
            $data[$key]['name'] = $value->sekolah->nama_sekolah;
        }
        
        return response()->json($data);
    }
    public function getForm(Request $request)
    {
        if(@$request->sekolah){
            $sekolahId = decode_id($request->sekolah);
        }else{
            $sekolahId = session('sekolah_id');
        }
        
        $title  = FormKriteria::select('kategori')->where('tahun',tahunKuesioner($request->kuesionerId))->where('page_number',$request->page)->first();
        $data = formKriteria($request->page,$sekolahId,@$request->type,tahunKuesioner($request->kuesionerId));
        $nilai_sekolah  = Penilaian::where('ms_sekolah_id',$sekolahId)
        ->where('page_number',$request->page)
        ->where('skor','!=',0)
        ->where('tahun',date('Y'))
        ->where('status',0) //inputan sekolah
        ->first();

        $nilai_kota  = Penilaian::where('ms_sekolah_id',$sekolahId)
        ->where('page_number',$request->page)
        ->where('skor','!=',0)
        ->where('tahun',date('Y'))
        ->where('status',1) //inputan kota
        ->first();

        $nilai_prov  = Penilaian::where('ms_sekolah_id',$sekolahId)
        ->where('page_number',$request->page)
        ->where('skor','!=',0)
        ->where('tahun',date('Y'))
        ->where('status',2) //inputan kota
        ->first();

        return response()->json(
            [
                'status'        => true, 
                'data'          => $data,
                'title'         => $title->kategori,
                'nilai_sekolah' => @$nilai_sekolah ? @$nilai_sekolah->skor : 0,
                'nilai_kota'    => @$nilai_kota ? @$nilai_kota->skor : 0,
                'nilai_prov'    => @$nilai_prov ? @$nilai_prov->skor : 0,
            ]
        );
    }
    public function getKabupaten(Request $request)
    {
        $_data = [];
        if(@$request->id){
            $keyId = decode_id($request->id);
            $data = Kabupaten::where('ms_provinsi_id',$keyId)->get();
            foreach($data as $k => $val){
                $_data[$k]['id'] = encode_id($val->MsKabupatenId);
                $_data[$k]['name'] = $val->name;
            }
        }
        return response()->json(['status' => true, 'data' => $_data]);
    }
    public function getKecamatan(Request $request)
    {
        $_data = [];
        if(@$request->id){
            $keyId = decode_id($request->id);
            $data = Kecamatan::where('ms_kabupaten_id',$keyId)->get();
            foreach($data as $k => $val){
                $_data[$k]['id'] = encode_id($val->MsKecamatanId);
                $_data[$k]['name'] = $val->name;
            }
        }
        return response()->json(['status' => true, 'data' => $_data]);
    }

    public function getSekolah(Request $request)
    {
        $_data = [];
        if(@$request->id){
            $keyId = decode_id($request->id);
            $data = Sekolah::where('ms_kecamatan_id',$keyId)->get();
            foreach($data as $k => $val){
                $_data[$k]['id'] = encode_id($val->MsSekolahId);
                $_data[$k]['name'] = $val->nama_sekolah;
                $_data[$k]['npsn'] = $val->npsn;
            }
        }
        return response()->json(['status' => true, 'data' => $_data]);
    }
}
