<?php

namespace App\Http\Controllers\Forms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\FormUpCountry;
use App\Models\Rayon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Region;
use App\Models\Cabang;
use App\Models\UserHasCabang;
use App\Models\Kategori;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ExpenseApproved;
use App\Mail\ExpenseRejected;
use App\Mail\FinalApprove;
use App\Mail\ExpenseCreated;
use App\Helpers\WhatsappHelper;
use App\Helpers\AuditTrailHelper;
use App\Helpers\NextCloudHelper;
use App\Rules\FileType;
use App\Models\Admin;
use App\Helpers\BudgetHelper;

class FormUpCountryController extends Controller
{
  public function index()
  {
    $this->checkAuthorization(auth()->user(), ['forms.country.view']);

    $role = auth()->user()->getRoleNames()[0];
    $forms = FormUpCountry::whereMonth('tanggal', date('m'))
      ->whereYear('tanggal', date('Y'))
      ->where('tanggal', '<=', date('Y-m-20'))
      ->whereRaw('DAY(CURDATE()) <= 20')
      ->orderBy('tanggal', 'desc')
      ->get();

    $availableBudget = null;

		if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
			$region_id = auth()->user()->getMyCabangAndRegionId()['region'];

			if ($region_id) {
				$users = UserHasCabang::whereHas('cabang', function ($query) use ($region_id) {
					$query->where('region_id', $region_id);
				})->get();

				$userIds = $users->pluck('user_id')->toArray();
				$forms = $forms->whereIn('user_id', $userIds);
			}
		}
    else if ($role == 'Area Manager Cabang') {
      $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

      if ($cabang_id) {
        $users = UserHasCabang::where('cabang_id', $cabang_id)->get();
        $userIds = $users->pluck('user_id')->toArray();
        $forms = $forms->whereIn('user_id', $userIds);
        $availableBudget = BudgetHelper::getAvailableBudget($cabang_id);
      }
    }
    else if ($role == 'Medical Representatif') {
      $forms = $forms->where('user_id', auth()->user()->id);
      $cabang_id = UserHasCabang::where('user_id', auth()->user()->id)->first()->cabang_id;

      $availableBudget = BudgetHelper::getAvailableBudget($cabang_id);
    } 
    else {
      $forms = $forms;
    }

    session()->put('redirect_url', route('forms.up-country'));
		return view('backend.pages.forms.upcountry.index', [
			'forms' => $forms,
      'availableBudget' => $availableBudget
		]);
	}

  public function detail($id)
  {
    $this->checkAuthorization(auth()->user(), ['forms.country.view']);

    $form = FormUpCountry::with(['rayon', 'user'])->findOrFail($id);
    $form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null;
    $form->bukti_transport_dalkot = $form->bukti_transport_dalkot ? NextCloudHelper::getFileUrl($form->bukti_transport_dalkot) : null;
    $form->bukti_transport_ankot = $form->bukti_transport_ankot ? NextCloudHelper::getFileUrl($form->bukti_transport_ankot) : null;
    $form->bukti_hotel = $form->bukti_hotel ? NextCloudHelper::getFileUrl($form->bukti_hotel) : null;

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

  public function view($id)
  {
    $this->checkAuthorization(auth()->user(), ['forms.country.view']);

    $form = FormUpCountry::with(['rayon', 'user'])->findOrFail($id);
    $form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null;
    $form->bukti_transport_dalkot = $form->bukti_transport_dalkot ? NextCloudHelper::getFileUrl($form->bukti_transport_dalkot) : null;
    $form->bukti_transport_ankot = $form->bukti_transport_ankot ? NextCloudHelper::getFileUrl($form->bukti_transport_ankot) : null;
    $form->bukti_hotel = $form->bukti_hotel ? NextCloudHelper::getFileUrl($form->bukti_hotel) : null;

    return view('backend.pages.forms.upcountry.view', [
      'form' => $form,
      'rayons' => Rayon::all(),
    ]);
  }

	public function create()
	{
    $this->checkAuthorization(auth()->user(), ['forms.country.create']);

		return view('backend.pages.forms.upcountry.create', [
			'rayons' => Rayon::all()
		]);
	}

	public function store(Request $request)
	{
    $this->checkAuthorization(auth()->user(), ['forms.country.create']);

    $request->validate([
      'rayon_id' => 'required|exists:rayon,id',
      'tanggal' => 'required',
      'tujuan' => 'required',
      'jarak' => 'required',
      'allowance' => 'nullable|numeric',
      'transport_dalkot' => 'nullable|numeric',
      'transport_ankot' => 'nullable|numeric',
      'hotel' => 'nullable|numeric',
      'bukti_allowance' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_transport_dalkot' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_transport_ankot' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_hotel' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
    ]);

    $cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang;
    $region = Region::where('id', $cabang->region_id)->first();
    $kategori = Kategori::where('name', 'Up Country')->first();

    $filePaths = [];
    $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/upcountry';

		if ($request->hasFile('bukti_allowance')) {
      $bukti_allowance = $request->file('bukti_allowance');
			$filename = Str::uuid() . '.' . $bukti_allowance->extension();

			$filePaths['bukti_allowance'] = $folderPath . '/' . $filename;

      NextCloudHelper::uploadFile(
        $folderPath,
        $bukti_allowance->getContent(),
				$filename
      );

    }
    if ($request->hasFile('bukti_transport_dalkot')) {
      $bukti_transport_dalkot = $request->file('bukti_transport_dalkot');
			$filename = Str::uuid() . '.' . $bukti_transport_dalkot->extension();

			$filePaths['bukti_transport_dalkot'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_transport_dalkot->getContent(),
				$filename
			);
    }
    if ($request->hasFile('bukti_transport_ankot')) {
      $bukti_transport_ankot = $request->file('bukti_transport_ankot');
			$filename = Str::uuid() . '.' . $bukti_transport_ankot->extension();

			$filePaths['bukti_transport_ankot'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_transport_ankot->getContent(),
				$filename
			);
    }
    if ($request->hasFile('bukti_hotel')) {
      $bukti_hotel = $request->file('bukti_hotel');
			$filename = Str::uuid() . '.' . $bukti_hotel->extension();

			$filePaths['bukti_hotel'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_hotel->getContent(),
				$filename
			);
    }

    // Generate sequence number and expense number
		$sequence_number = FormUpCountry::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-UPC-' . date('ym') . '%')->count() + 1;
    $formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT);
    $expense_number = $region->code . '-' . $cabang->code . '-UPC-' . date('ym') . $formatted_sequence_number;

    $data_nominal = [
      'allowance' => $request->allowance ?? 0,
      'transport_dalkot' => $request->transport_dalkot ?? 0,
      'transport_ankot' => $request->transport_ankot ?? 0,
      'hotel' => $request->hotel ?? 0,
    ];

    // Check if the total nominal exceeds the available budget
    $cabang_id = UserHasCabang::where('user_id', auth()->user()->id)->first()->cabang_id;
    if(array_sum($data_nominal) > BudgetHelper::getAvailableBudget($cabang_id)) {
      session()->flash('error', 'The total nominal exceeds the available budget.');
      return redirect()->back();
    }

    // Save the form data
    $form = FormUpCountry::create([
      'expense_number' => $expense_number,
      'user_id' => auth()->user()->id,
      'rayon_id' => $request->rayon_id,
      'tanggal' => $request->tanggal,
      'tujuan' => $request->tujuan,
      'jarak' => $request->jarak,
      'allowance' => $data_nominal['allowance'],
      'transport_dalkot' => $data_nominal['transport_dalkot'],
      'transport_ankot' => $data_nominal['transport_ankot'],
      'hotel' => $data_nominal['hotel'],
      'total' => array_sum($data_nominal),
      'bukti_allowance' => $filePaths['bukti_allowance'] ?? null,
      'bukti_transport_dalkot' => $filePaths['bukti_transport_dalkot'] ?? null,
      'bukti_transport_ankot' => $filePaths['bukti_transport_ankot'] ?? null,
      'bukti_hotel' => $filePaths['bukti_hotel'] ?? null,
      'account_number' => $kategori->account_number,
      'status' => 'On Progress',
    ]);

    // Send notification to MIS and Admin Region
    $roles = ['Marketing Information System', 'Admin Region'];
    $recipients = [];
    $phoneNumbers = [];

    $name = auth()->user()->name;
    $tanggal = $form->tanggal;
    $total = $form->total;

    // Collect all recipients (emails and phone numbers) for the specified roles
    foreach ($roles as $role) {
      $users = Admin::getUserByRoleName($role);
      foreach ($users as $user) {
        $recipients[] = $user->email;
        $phoneNumbers[] = $user->phone;
      }
    }

    // Remove duplicate email addresses, if any
    $recipients = array_unique($recipients);

    // Generate URL and send WhatsApp notification
    $url = route('forms.up-country.view', $form->id);
    WhatsappHelper::newExpense($phoneNumbers, $expense_number, $url);

    // Send bulk email
    Mail::to($recipients)->send(new ExpenseCreated(
      $name,
      $expense_number,
      $tanggal,
      $total,
      $url
    ));

    AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Up Country (' . $expense_number . ')');
    session()->flash('success', 'Form has been created.');
    return redirect()->back();
	}

	public function edit($id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.country.edit']);
    $role = auth()->user()->getRoleNames()[0];

    $form = FormUpCountry::with('rayon')->findOrfail($id);
    if($form->status != 'On Progress' && $role == 'Medical Representatif') {
      session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
      return redirect()->back();
    }
    
		return view('backend.pages.forms.upcountry.edit', [
			'rayons' => Rayon::all(),
      'form' => $form
		]);
	}

	public function update(Request $request, $id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.country.edit']);
    $role = auth()->user()->getRoleNames()[0];

    $request->validate([
      'rayon_id' => 'required|exists:rayon,id',
      'tanggal' => 'required',
      'tujuan' => 'required',
      'jarak' => 'required',
      'allowance' => 'nullable|numeric',
      'transport_dalkot' => 'nullable|numeric',
      'transport_ankot' => 'nullable|numeric',
      'hotel' => 'nullable|numeric',
      'bukti_allowance' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_transport_dalkot' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_transport_ankot' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
      'bukti_hotel' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
    ]);

    $form = FormUpCountry::findOrfail($id);
    if($form->status != 'On Progress' && $role == 'Medical Representatif') {
      session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
      return redirect()->back();
    }

    $cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()->cabang;
    $region = Region::where('id', $cabang->region_id)->first();
    $kategori = Kategori::where('name', 'Up Country')->first();

    $filePaths = [];
    $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/upcountry';

    if ($request->hasFile('bukti_allowance')) {
      $bukti_allowance = $request->file('bukti_allowance');
			$filename = Str::uuid() . '.' . $bukti_allowance->extension();

			$filePaths['bukti_allowance'] = $folderPath . '/' . $filename;

      NextCloudHelper::uploadFile(
        $folderPath,
        $bukti_allowance->getContent(),
				$filename
      );

    }
    if ($request->hasFile('bukti_transport_dalkot')) {
      $bukti_transport_dalkot = $request->file('bukti_transport_dalkot');
			$filename = Str::uuid() . '.' . $bukti_transport_dalkot->extension();

			$filePaths['bukti_transport_dalkot'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_transport_dalkot->getContent(),
				$filename
			);
    }
    if ($request->hasFile('bukti_transport_ankot')) {
      $bukti_transport_ankot = $request->file('bukti_transport_ankot');
			$filename = Str::uuid() . '.' . $bukti_transport_ankot->extension();

			$filePaths['bukti_transport_ankot'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_transport_ankot->getContent(),
				$filename
			);
    }
    if ($request->hasFile('bukti_hotel')) {
      $bukti_hotel = $request->file('bukti_hotel');
			$filename = Str::uuid() . '.' . $bukti_hotel->extension();

			$filePaths['bukti_hotel'] = $folderPath . '/' . $filename;

			NextCloudHelper::uploadFile(
				$folderPath,
				$bukti_hotel->getContent(),
				$filename
			);
    }

    $data_nominal = [
      'allowance' => $request->allowance ?? 0,
      'transport_dalkot' => $request->transport_dalkot ?? 0,
      'transport_ankot' => $request->transport_ankot ?? 0,
      'hotel' => $request->hotel ?? 0,
    ];

    // Check if the total nominal exceeds the available budget
    $cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()->cabang_id;
    if(array_sum($data_nominal) > BudgetHelper::getAvailableBudget($cabang_id)) {
      session()->flash('error', 'The total nominal exceeds the available budget.');
      return redirect()->back();
    }

    // Save the form data
    $form->update([
      'rayon_id' => $request->rayon_id,
      'tanggal' => $request->tanggal,
      'tujuan' => $request->tujuan,
      'jarak' => $request->jarak,
      'allowance' => $data_nominal['allowance'],
      'transport_dalkot' => $data_nominal['transport_dalkot'],
      'transport_ankot' => $data_nominal['transport_ankot'],
      'hotel' => $data_nominal['hotel'],
      'total' => array_sum($data_nominal),
      'bukti_allowance' => $filePaths['bukti_allowance'] ?? $form->bukti_allowance,
      'bukti_transport_dalkot' => $filePaths['bukti_transport_dalkot'] ?? $form->bukti_transport_dalkot,
      'bukti_transport_ankot' => $filePaths['bukti_transport_ankot'] ?? $form->bukti_transport_ankot,
      'bukti_hotel' => $filePaths['bukti_hotel'] ?? $form->bukti_hotel,
      'account_number' => $kategori->account_number,
    ]);

    AuditTrailHelper::AddAuditTrail('Update', 'Update Record at Form Up Country (' . $form->expense_number . ')');
    session()->flash('success', 'Form has been updated.');
    return redirect()->back();
	}

  public function approve(Request $request, $id)
  {
    $this->checkAuthorization(auth()->user(), ['approval.approve']);

    $form = FormUpCountry::findOrfail($id);
    $approved_data = [
      'allowance' => $request->allowance ? $form->allowance : 0,
      'transport_dalkot' => $request->transport_dalkot ? $form->transport_dalkot : 0,
      'transport_ankot' => $request->transport_ankot ? $form->transport_ankot : 0,
      'hotel' => $request->hotel ? $form->hotel : 0,
    ];

    // Check if the total nominal exceeds the available budget
    $cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()->cabang_id;
    if(array_sum($approved_data) > BudgetHelper::getAvailableBudget($cabang_id)) {
      session()->flash('error', 'The total nominal exceeds the available budget.');
      return redirect()->back();
    }

    $form->update([
      'approved_at' => now(),
      'approved_by' => auth()->user()->id,
      'status' => 'Approved',
      'approved_allowance' => $approved_data['allowance'],
      'approved_transport_dalkot' => $approved_data['transport_dalkot'],
      'approved_transport_ankot' => $approved_data['transport_ankot'],
      'approved_hotel' => $approved_data['hotel'],
      'approved_total' => array_sum($approved_data),
    ]);

    $heads = $form->user->getCabangAndRegionHead();
    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->tanggal;
    $total = $form->approved_total;

    // Collect all recipients
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];

    if ($heads['cabang_head']) {
      $recipients[] = $heads['cabang_head']['email'];
      $phoneNumbers[] = $heads['cabang_head']['phone'];
    }

    if ($heads['region_head']) {
      $recipients[] = $heads['region_head']['email'];
      $phoneNumbers[] = $heads['region_head']['phone'];
    }

    // Remove duplicate data, if any
    $recipients = array_unique($recipients);
    $phoneNumbers = array_unique($phoneNumbers);

    // send whatsapp message
    $url = route('forms.up-country.view', $form->id);
    WhatsappHelper::approveExpense($phoneNumbers, $expense_number, $url);

    // // Send bulk email
    Mail::to($recipients)->send(new ExpenseApproved(
      $name,
      $expense_number,
      $tanggal,
      $total,
      $url
    ));

    AuditTrailHelper::AddAuditTrail('Approve', 'Approve Expense at Form Up Country (' . $form->expense_number . ')');
    session()->flash('success', 'Form has been approved.');
    return redirect()->back();
  }

  public function reject($id)
  {
    $this->checkAuthorization(auth()->user(), ['approval.approve']);

    $form = FormUpCountry::findOrfail($id);
    $form->update([
      'status' => 'Rejected'
    ]);

    $heads = $form->user->getCabangAndRegionHead();
    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->tanggal;
    $total = $form->total;

    // Collect all recipients
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];

    if ($heads['cabang_head']) {
      $recipients[] = $heads['cabang_head']['email'];
      $phoneNumbers[] = $heads['cabang_head']['phone'];
    }

    if ($heads['region_head']) {
      $recipients[] = $heads['region_head']['email'];
      $phoneNumbers[] = $heads['region_head']['phone'];
    }

    // Remove duplicate email addresses, if any
    $recipients = array_unique($recipients);
    $phoneNumbers = array_unique($phoneNumbers);

    // send whatsapp message
    $url = route('forms.up-country.view', $form->id);
    WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url);

    // Send bulk email
    Mail::to($recipients)->send(new ExpenseRejected(
      $name,
      $expense_number,
      $tanggal,
      $total,
      $url
    ));

    AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Up Country (' . $form->expense_number . ')');
    session()->flash('success', 'Form has been rejected.');
    return redirect()->back();
  }

  public function finalApprove($id)
  {
    $this->checkAuthorization(auth()->user(), ['final_approval.approve']);

    $form = FormUpCountry::findOrfail($id);
    if($form->approved_at == null) {
      session()->flash('error', 'Form must be approved by MIS first.');
      return redirect()->back();
    }

    $form->update([
      'final_approved_at' => now(),
      'final_approved_by' => auth()->user()->id,
      'status' => 'Closed'
    ]);

    $heads = $form->user->getCabangAndRegionHead();
    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->tanggal;
    $total = $form->approved_total;

    // Collect all recipients
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];

    if ($heads['cabang_head']) {
      $recipients[] = $heads['cabang_head']['email'];
      $phoneNumbers[] = $heads['cabang_head']['phone'];
    }

    if ($heads['region_head']) {
      $recipients[] = $heads['region_head']['email'];
      $phoneNumbers[] = $heads['region_head']['phone'];
    }

    // Remove duplicate email addresses, if any
    $recipients = array_unique($recipients);
    $phoneNumbers = array_unique($phoneNumbers);

    // send whatsapp message
    $url = route('forms.up-country.view', $form->id);
    WhatsappHelper::finalApprove($phoneNumbers, $expense_number, $url);

    // Send bulk email
    Mail::to($recipients)->send(new FinalApprove(
      $name,
      $expense_number,
      $tanggal,
      $total,
      $url
    ));

    AuditTrailHelper::AddAuditTrail('Final Approve', 'Final Approve Expense at Form Up Country (' . $form->expense_number . ')');
    session()->flash('success', 'Form has been final approved.');
    return redirect()->back();
  }

  public function open($id)
  {
    $this->checkAuthorization(auth()->user(), ['final_approval.open']);

    $form = FormUpCountry::findOrfail($id);
    $form->update([
      'final_approved_at' => null,
      'final_approved_by' => null,
      'status' => 'Approved'
    ]);

    AuditTrailHelper::AddAuditTrail('Open', 'Open Expense at Form Up Country (' . $form->expense_number . ')');
    session()->flash('success', 'Form has been opened.');
    return redirect()->back();
  }

	public function destroy($id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.country.delete']);
    $role = auth()->user()->getRoleNames()[0];
    
		$form = FormUpCountry::findOrfail($id);
    if($form->status != 'On Progress' && $role == 'Medical Representatif') {
      session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
      return redirect()->back();
    }

    AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Up Country (' . $form->expense_number . ')');
    
		$form->delete();

		session()->flash('success', 'Form has been deleted.');
		return redirect()->back();
	}
}