<?php

namespace App\Http\Controllers\EndoBOOK;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;
use App\Models\Server;
use Carbon\Carbon;
use Image;
use DateTime;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\Bookexport;
use App\Models\Department;

class BookExportController extends Controller
{

    public function index(Request $r)
    {

    }

    public function show($date){
        $view['hospital']      = getCONFIG("hospital");
        $view['department']    = uget("department");
        $department             = uget("department");
        $view['departments']    = Server::table('tb_department')->get();
        $view['doctor']         = Department::user('doctor', uid());
        $view['booking']        = getCONFIG("booking");
        $view['procedure']      = Department::procedure(uid());
        $view["tb_booking"]     = Server::table("tb_booking")
        ->where("date" , $date)
        ->where("department", $department)
        ->get();
        $view['count_case']     = Server::table("tb_booking")->where("date" , $date)->count();
        $view['dateformat']     = $this->convertToThaiDate($date);

        return view("EndoBOOK.bookingviewer.schedulesum", ['id' => $date] , $view);

    }

    public function convertToThaiDate($date){
        $months = [
            1 => 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน',
            'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
        ];

        $dateParts = explode('-', $date);
        $year = (int)$dateParts[0] + 543; // Convert to Buddhist year
        $month = (int)$dateParts[1];
        $day = (int)$dateParts[2];

        return sprintf('%d %s %d', $day, $months[$month], $year);
    }

    public function edit($id){
        session_start();
        $_SESSION['download_start'] = $id * 10000;
        $end    = $_SESSION['download_start'] + 10000;
        $bank   = new Bookexport;
        return Excel::download($bank, 'report' . ".xls");
    }
}
