<?php

namespace App\Http\Controllers\Forms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\FormMeetingSeminar;
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 App\Helpers\NextCloudHelper;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ExpenseApproved;
use App\Mail\ExpenseRejected;
use App\Helpers\WhatsappHelper;

class FormMeetingSeminarController extends Controller
{
  public function index()
  {
    $this->checkAuthorization(auth()->user(), ['forms.meeting.view']);
    
    // get user role
    $role = auth()->user()->getRoleNames()[0];
    $forms = null;

    if($role == 'Marketing Information System' || $role == 'superadmin') {
      $forms = FormMeetingSeminar::get();
    } else {
      $forms = FormMeetingSeminar::where('user_id', auth()->user()->id)->get();
    }

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

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

		return view('backend.pages.forms.meeting.create');
	}

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

    $request->validate([
      'allowance' => 'required',
      'transport_ankot' => 'required',
      'hotel' => 'required',
      'bukti1' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      'bukti2' => 'nullable|file|mimes:xlsx,xls,csv',
      'bukti3' => 'nullable|file|mimes:pdf',
    ]);

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

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

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

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

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

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

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

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

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

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

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

    // Save the form data
    FormMeetingSeminar::create([
      'expense_number' => $expense_number,
      'user_id' => auth()->user()->id,
      'allowance' => $request->allowance,
      'transport_ankot' => $request->transport_ankot,
      'hotel' => $request->hotel,
      'total' => $request->allowance + $request->transport_ankot + $request->hotel,
      'bukti1' => $filePaths['bukti1'] ?? null,
      'bukti2' => $filePaths['bukti2'] ?? null,
      'bukti3' => $filePaths['bukti3'] ?? null,
      'account_number' => $kategori->account_number,
      'status' => 'On Progress',
    ]);

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

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

    $form = FormMeetingSeminar::findOrfail($id);
    if($form->status == 'Closed') {
      session()->flash('error', 'Form has been closed, you cannot edit it.');
      return redirect()->back();
    }
    
		return view('backend.pages.forms.meeting.edit', [
      'form' => $form
		]);
	}

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

    $request->validate([
      'allowance' => 'required',
      'transport_ankot' => 'required',
      'hotel' => 'required',
      'bukti1' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      'bukti2' => 'nullable|file|mimes:xlsx,xls,csv',
      'bukti3' => 'nullable|file|mimes:pdf',
    ]);

    $form = FormMeetingSeminar::findOrfail($id);
    if($form->status == 'Closed') {
      session()->flash('error', 'Form has been closed, you cannot edit it.');
      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', 'Meeting & Seminar')->first();

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

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

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

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

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

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

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

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

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

    // Save the form data
    $form->update([
      'allowance' => $request->allowance,
      'transport_ankot' => $request->transport_ankot,
      'hotel' => $request->hotel,
      'total' => $request->allowance + $request->transport_ankot + $request->hotel,
      'bukti1' => $filePaths['bukti1'] ?? $form->bukti1,
      'bukti2' => $filePaths['bukti2'] ?? $form->bukti2,
      'bukti3' => $filePaths['bukti3'] ?? $form->bukti3,
      'account_number' => $kategori->account_number,
    ]);

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

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

    $form = FormMeetingSeminar::findOrfail($id);
    $form->update([
      'approved_at' => now(),
      'approved_by' => auth()->user()->id,
      'status' => 'Approved'
    ]);

    $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];
    $phoneNumbers = [$form->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 bulk email
    Mail::to($recipients)->send(new ExpenseApproved(
      $name,
      $expense_number,
      $tanggal,
      $total
    ));

    // Send bulk WhatsApp message
    WhatsappHelper::approveExpense($phoneNumbers, $expense_number);

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

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

    $form = FormMeetingSeminar::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'
    ]);

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

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

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

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

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

    $form = FormMeetingSeminar::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];
    $phoneNumbers = [$form->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 bulk email
    Mail::to($recipients)->send(new ExpenseRejected(
      $name,
      $expense_number,
      $tanggal,
      $total
    ));

    // Send bulk WhatsApp message
    WhatsappHelper::rejectExpense($phoneNumbers, $expense_number);

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

	public function destroy($id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.meeting.delete']);
    
		$form = FormMeetingSeminar::findOrfail($id);
		$form->delete();

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