<?php

namespace App\Http\Controllers;

use App\Audit;
use App\WakilSurat;
use App\Cawangan;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use Carbon\Carbon;

class WakilController extends Controller
{

    public function showSuratWakilByNorujukan($kodcaw, $norujukan)
    {

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $check_norujukan = WakilSurat::on($cawangan['mysql'])
            ->where('norujukan', '=', $norujukan)
            ->get();

        if (sizeof($check_norujukan) != 0) {
            $newnorujukan = $norujukan;
        } else {

            $newnorujukan = 'NULL';
        }
        return response()->json($newnorujukan);
    }


    public function showsuratwakil($kodcaw, $t_cetak)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $wakil_surat = WakilSurat::on($cawangan['mysql'])->where('t_cetak', '=', $t_cetak)->orderBy('id', 'desc')->first();

        return response()->json($wakil_surat);
    }

    public function createSuratWakil($kodcaw, Request $request)
    {
        $harini = Carbon::now();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $wakil = WakilSurat::on($cawangan['mysql'])->create([
            'nosiri' => $request->nosiri,
            'no_surat' => $request->no_surat,
            'norujukan' => $request->norujukan,
            't_cetak' => $request->t_cetak

        ]);

        $audit = new Audit();
        $audit->users = $request->nama;
        $audit->actions = "Cetak Surat Wakil";
        $audit->norujukan = $request->norujukan;
        $audit->new_data = $wakil;
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $harini;
        $audit->updated_at = $harini;
        $audit->save();

        return response()->json($wakil);
    }

    public function noSiriWakil($kodcaw, $norujukan)
    {

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $getnosiri = WakilSurat::on($cawangan['mysql'])
            ->where('norujukan', '=', $norujukan)
            ->select('no_surat')
            ->get();

        $nosiri = $getnosiri[0]['no_surat'];

        return response()->json($nosiri);
    }

    public function updateWakil($kodcaw, $norujukan)
    {
        $current = Carbon::now();
        $current = new Carbon();


        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $update_wakil = WakilSurat::on($cawangan['mysql'])->where('norujukan', '=', $norujukan)
        ->update(array(
            't_cetak' => $current->toDateString(),
            'updated_at' => $current
        ));

        return response()->json($update_wakil, 200);
    }
}
