<?php

namespace App\Controllers;
use App\Models\LombaModel;

class Homepage extends BaseController{

public function index(){
    echo view('homepage/homepage');
}

public function daftar(){
    echo view('homepage/pendaftaran');
}

public function submit(){
    $lombaModel = new LombaModel();
    $validation =  \Config\Services::validation();

    $validation->setRules([
        'nama' => 'required|min_length[3]|max_length[255]',
        'tempat_lahir' => 'required',
        'tanggal_lahir' => 'required|valid_date',
        'nomor_hp' => 'required|numeric|min_length[10]|max_length[13]',
        'nisn' => 'required|exact_length[10]|numeric',
        'alamat' => 'required',
        'jenis_lomba' => 'required',
        'link_video' => 'required|valid_url',
        'screenshot_follow' => 'uploaded[screenshot_follow]|max_size[screenshot_follow,2048]|ext_in[screenshot_follow,jpg,jpeg,png]',
        'bukti_pembayaran' => 'uploaded[bukti_pembayaran]|max_size[bukti_pembayaran,2048]|ext_in[bukti_pembayaran,jpg,jpeg,png]',
        'file_rapor' => 'uploaded[file_rapor]|max_size[file_rapor,2048]|ext_in[file_rapor,pdf,jpg,jpeg,png]',
    ]);

    if (!$validation->withRequest($this->request)->run()) {
        // Jika validasi gagal, kembalikan ke form dengan error
        return redirect()->back()->withInput()->with('validation', $validation);
    }

     // Upload file
     $screenshot_follow = $this->request->getFile('screenshot_follow');
     $bukti_pembayaran = $this->request->getFile('bukti_pembayaran');
     $file_rapor = $this->request->getFile('file_rapor');

     // Simpan file di direktori public/uploads
     $screenshot_follow_name = $screenshot_follow->getRandomName();
     $bukti_pembayaran_name = $bukti_pembayaran->getRandomName();
     $file_rapor_name = $file_rapor->getRandomName();

     $screenshot_follow->move(FCPATH . 'uploads', $screenshot_follow_name);
     $bukti_pembayaran->move(FCPATH . 'uploads', $bukti_pembayaran_name);
     $file_rapor->move(FCPATH . 'uploads', $file_rapor_name);

    // Data yang akan disimpan ke database
    $data = [
        'nama' => $this->request->getPost('nama'),
        'tempat_lahir' => $this->request->getPost('tempat_lahir'),
        'tanggal_lahir' => $this->request->getPost('tanggal_lahir'),
        'nomor_hp' => $this->request->getPost('nomor_hp'),
        'nisn' => $this->request->getPost('nisn'),
        'alamat' => $this->request->getPost('alamat'),
        'jenis_lomba' => $this->request->getPost('jenis_lomba'),
        'link_video' => $this->request->getPost('link_video'),
        'ss_follow' => $screenshot_follow_name,
        'bukti_pembayaran' => $bukti_pembayaran_name,
        'file_rapor' => $file_rapor_name,
    ];
    
    $lombaModel->insert($data);

    return redirect()->to(base_url('/daftar/sukses'));
}

public function sukses(){
    echo view('homepage/sukses');
}

}