<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Cuti extends Model
{
    use HasFactory;
    
    protected $table = 'cuti';
    
    protected $fillable = [
        'user_id',
        'nama',
        'jenis_cuti',
        'tanggal_mulai',
        'tanggal_selesai',
        'keterangan',
        'status',
        'file_pdf',
        'approved_by',
        'approved_at',
        'rejected_by',
        'rejected_at'
    ];

    protected $casts = [
        'tanggal_mulai' => 'date',
        'tanggal_selesai' => 'date',
        'approved_at' => 'datetime',
        'rejected_at' => 'datetime',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function rejecter()
    {
        return $this->belongsTo(User::class, 'rejected_by');
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required|string',
            'jenis_cuti' => 'required|string',
            'keterangan' => 'required|string',
            'tanggal_mulai' => 'required|date',
            'tanggal_selesai' => 'required|date',
            'file' => 'required|mimes:pdf|max:2048', // Validate PDF file
        ]);

        $filePath = $request->file('file')->store('cuti_files', 'public');

        Cuti::create([
            'user_id' => auth()->id(),
            'nama' => $request->nama,
            'jenis_cuti' => $request->jenis_cuti,
            'keterangan' => $request->keterangan,
            'tanggal_mulai' => $request->tanggal_mulai,
            'tanggal_selesai' => $request->tanggal_selesai,
            'status' => 'Pending',
            'file_path' => $filePath, // Save file path
        ]);

        return response()->json(['success' => true, 'message' => 'Cuti submitted successfully']);
    }
} 