<?php

namespace App\Http\Controllers\Forms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\FormOthers;
use App\Models\Region;
use App\Models\UserHasCabang;
use App\Models\Kategori;
use Illuminate\Support\Str;
use App\Helpers\NextCloudHelper;
use Illuminate\Support\Facades\Mail;
use App\Mail\ExpenseApproved;
use App\Mail\ExpenseApproved2;
use App\Mail\ExpenseRejected;
use App\Mail\FinalApprove;
use App\Mail\ExpenseCreated;
use App\Helpers\WhatsappHelper;
use App\Helpers\AuditTrailHelper;
use App\Rules\FileType;
use App\Models\Admin;
use App\Helpers\BudgetHelper;
use App\Helpers\NotificationHelper;
use App\Models\Cabang;
use Illuminate\Support\Facades\Log;

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

    $role = auth()->user()->getRoleNames()[0];
    $startDate = date('Y-m-' . env('STARTING_DATE')); // Starting date from .env for the current month
    $closingDateNextMonth = date('Y-m-', strtotime('+1 month')) . env('CLOSING_DATE'); // Closing date for the next month

    $forms = FormOthers::whereBetween('tanggal', [$startDate, $closingDateNextMonth])
      ->orderBy('tanggal', 'desc')
      ->with('user')
      ->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;
    }

    dd($startDate, $closingDateNextMonth, $forms, $availableBudget);

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

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

    $form = FormOthers::with(['user', 'kategori'])->findOrFail($id);
    $form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null;

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

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

    $form = FormOthers::with(['user', 'kategori'])->findOrFail($id);
    $form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null;

    return view('backend.pages.forms.other.view', [
      'form' => $form,
      'kategori' => Kategori::whereNotIn('name', ['Up Country', 'Vehicle Running Cost', 'Entertainment', 'Meeting / Seminar'])->get()
    ]);
  }

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

		return view('backend.pages.forms.other.create', [
      'kategori' => Kategori::whereNotIn('name', ['Up Country', 'Vehicle Running Cost', 'Entertainment', 'Meeting / Seminar'])->get()
    ]);
	}

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

    $request->validate([
      'kategori_id' => 'required',
      'tanggal' => 'required|date',
      'keterangan' => 'required',
      'total' => 'required|numeric|min:1',
      'bukti_total' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
    ]);

    $startDate = date('Y-m-' . env('STARTING_DATE'));
    $closingDateNextMonth = date('Y-m-', strtotime('+1 month')) . env('CLOSING_DATE');

    if ($request->tanggal < $startDate || $request->tanggal > $closingDateNextMonth) {
      session()->flash('error', 'Gagal, Input expense sudah melewati periode input 12-10');
      return redirect()->back();
    }

    $cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang;
    if($request->total > BudgetHelper::getAvailableBudget($cabang->id)) {
      session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya');
      return redirect()->back();
    }

    $region = Region::where('id', $cabang->region_id)->first();
    $kategori = Kategori::where('id', $request->kategori_id)->first();

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

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

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

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

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

    // Save the form data
    $form = FormOthers::create([
      'expense_number' => $expense_number,
      'user_id' => auth()->user()->id,
      'kategori_id' => $request->kategori_id,
      'tanggal' => $request->tanggal,
      'keterangan' => $request->keterangan,
      'total' => $request->total,
      'bukti_total' => $filePaths['bukti_total'] ?? null,
      'account_number' => $kategori->account_number,
      'status' => 'On Progress',
    ]);

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

    // Send notification to MIS and Admin Region and Area Manager Cabang
    $roles = ['Marketing Information System', 'Admin Region', 'Area Manager Cabang'];
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];
    $receiver_ids = [];

    // Collect all recipients (emails and phone numbers) for the specified roles
    $cabang = UserHasCabang::where('user_id', $form->user_id)->first();
    $cabang_id = $cabang ? $cabang->cabang_id : null;

    $cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
    $region_id = $cabangData ? $cabangData->region->id : null;

    foreach ($roles as $role) {
      $users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
        if ($role === 'Marketing Information System') {
          return true; // Tidak ada filter cabang untuk peran ini
        }
        
        if (!$user->cabang || !$user->cabang->cabang) {
          return false; // Pastikan user memiliki cabang
        }

        if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
          return $user->cabang->cabang->region->id === $region_id;
        }

        return $user->cabang->cabang->id === $cabang_id; 
      });

      foreach ($users as $user) {
        $recipients[] = $user->email;
        $phoneNumbers[] = $user->phone;
        $receiver_ids[] = $user->id;
      }
    }

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

    $url = route('forms.other.view', $form->id);
    WhatsappHelper::newExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);

    // Send bulk email
    foreach ($recipients as $recipient) {
      try {
        Mail::to($recipient)->send(new ExpenseCreated(
          $name,
          $expense_number,
          $tanggal,
          $total,
          $url
        ));
      } catch (\Exception $e) {
        Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
        continue;
      }
    }

    // Send notification to the user
    NotificationHelper::newExpense('other', $form->id, $form->user_id, $expense_number, $receiver_ids);    

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

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

    $form = FormOthers::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.other.edit', [
      'form' => $form,
      'kategori' => Kategori::whereNotIn('name', ['Up Country', 'Vehicle Running Cost', 'Entertainment', 'Meeting / Seminar'])->get()
		]);
	}

	public function update(Request $request, $id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.other.edit']);
    $role = auth()->user()->getRoleNames()[0];
    $form = FormOthers::findOrfail($id);
    $cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()->cabang_id;

    $request->validate([
      'kategori_id' => 'required',
      'tanggal' => 'required|date',
      'keterangan' => 'required',
      'total' => 'required|numeric|min:1|max:' . BudgetHelper::getAvailableBudget($cabang_id),
      'bukti_total' => ['nullable', 'file', 'max:51200', new FileType(['php', 'exe', 'js', 'sh', 'bat', 'exe', 'sh', 'php', 'vbs'])],
    ]);

    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('id', $request->kategori_id)->first();

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

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

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

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

    // Save the form data
    $form->update([
      'kategori_id' => $request->kategori_id,
      'tanggal' => $request->tanggal,
      'keterangan' => $request->keterangan,
      'total' => $request->total,
      'bukti_total' => $filePaths['bukti_total'] ?? $form->bukti_total,
      'account_number' => $kategori->account_number,
    ]);

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

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

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

    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->created_at;
    $total = $form->total;

    // Collect all recipients
    $roles = ['Marketing Information System', 'Admin Region', 'Area Manager Cabang', 'Marketing Operational Manager Region'];
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];
    $receiver_ids = [];

    $cabang = UserHasCabang::where('user_id', $form->user_id)->first();
    $cabang_id = $cabang ? $cabang->cabang_id : null;

    $cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
    $region_id = $cabangData ? $cabangData->region->id : null;

    foreach ($roles as $role) {
      $users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
        if ($role === 'Marketing Information System') {
          return true; // Tidak ada filter cabang untuk peran ini
        }
        
        if (!$user->cabang || !$user->cabang->cabang) {
          return false; // Pastikan user memiliki cabang
        }

        if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
          return $user->cabang->cabang->region->id === $region_id;
        }

        return $user->cabang->cabang->id === $cabang_id; 
      });

      foreach ($users as $user) {
        $recipients[] = $user->email;
        $phoneNumbers[] = $user->phone;
        $receiver_ids[] = $user->id;
      }
    }

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

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

    // // Send bulk email
    foreach ($recipients as $recipient) {
      try {
        Mail::to($recipient)->send(new ExpenseApproved(
          $name,
          $expense_number,
          $tanggal,
          $total,
          $url
        ));
      } catch (\Exception $e) {
        Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
        continue;
      }
    }

    NotificationHelper::approveExpense('other', $form->id, $form->user_id, $expense_number, $receiver_ids);

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

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

    $form = FormOthers::findOrfail($id);
    $form->update([
      'approved2_at' => now(),
      'approved2_by' => auth()->user()->id,
      'status' => 'Approved 2',
    ]);

    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->created_at;
    $total = $form->total;

    $roles = ['Marketing Information System', 'Area Manager Cabang', 'Marketing Operational Manager Region', 'Head of Sales Marketing'];
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];
    $receiver_ids = [];

    $cabang = UserHasCabang::where('user_id', $form->user_id)->first();
    $cabang_id = $cabang ? $cabang->cabang_id : null;

    $cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
    $region_id = $cabangData ? $cabangData->region->id : null;

    foreach ($roles as $role) {
      $users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
        if ($role === 'Marketing Information System' || $role === 'Head of Sales Marketing') {
          return true; // Tidak ada filter cabang untuk peran ini
        }
        
        if (!$user->cabang || !$user->cabang->cabang) {
          return false; // Pastikan user memiliki cabang
        }

        if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
          return $user->cabang->cabang->region->id === $region_id;
        }

        return $user->cabang->cabang->id === $cabang_id; 
      });

      foreach ($users as $user) {
        $recipients[] = $user->email;
        $phoneNumbers[] = $user->phone;
        $receiver_ids[] = $user->id;
      }
    }

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

    // send whatsapp message
    $url = route('forms.other.view', $form->id);
    WhatsappHelper::approve2Expense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);

    // // Send bulk email
    foreach ($recipients as $recipient) {
      try {
        Mail::to($recipient)->send(new ExpenseApproved2(
          $name,
          $expense_number,
          $tanggal,
          $total,
          $url
        ));
      } catch (\Exception $e) {
        Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
        continue;
      }
    }

    NotificationHelper::approve2Expense('other', $form->id, $form->user_id, $expense_number, $receiver_ids);

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

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

    $form = FormOthers::findOrfail($id);
    if($form->approved_at == null || $form->approved2_at == null) {
      session()->flash('error', 'Form must be approved by both approvers before final approval.');
      return redirect()->back();
    }

    // Check if the total nominal exceeds the available budget
    $cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()->cabang_id;
    if($form->approved_total > BudgetHelper::getAvailableBudget($cabang_id)) {
      session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
      return redirect()->back();
    }

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

    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->created_at;
    $total = $form->approved_total;

    $roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
    $recipients = [$form->user->email, auth()->user()->email];
    $phoneNumbers = [$form->user->phone, auth()->user()->phone];

    $cabang = UserHasCabang::where('user_id', $form->user_id)->first();
    $cabang_id = $cabang ? $cabang->cabang_id : null;

    $cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
    $region_id = $cabangData ? $cabangData->region->id : null;

    foreach ($roles as $role) {
      $users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
        if ($role === 'Marketing Information System' || $role === 'Head of Sales Marketing') {
          return true; // Tidak ada filter cabang untuk peran ini
        }
        
        if (!$user->cabang || !$user->cabang->cabang) {
          return false; // Pastikan user memiliki cabang
        }

        if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
          return $user->cabang->cabang->region->id === $region_id;
        }

        return $user->cabang->cabang->id === $cabang_id; 
      });

      foreach ($users as $user) {
        $recipients[] = $user->email;
        $phoneNumbers[] = $user->phone;
      }
    }

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

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

    // Send bulk email
    foreach ($recipients as $recipient) {
      try {
        Mail::to($recipient)->send(new FinalApprove(
          $name,
          $expense_number,
          $tanggal,
          $total,
          $url
        ));
      } catch (\Exception $e) {
        Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
        continue;
      }
    }

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

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

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

    $heads = $form->user->getCabangAndRegionHead();
    $name = $form->user->name;
    $expense_number = $form->expense_number;
    $tanggal = $form->created_at;
    $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.other.view', $form->id);
    WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);

    // Send bulk email
    foreach ($recipients as $recipient) {
      try {
        Mail::to($recipient)->send(new ExpenseRejected(
          $name,
          $expense_number,
          $tanggal,
          $total,
          $url
        ));
      } catch (\Exception $e) {
        Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
        continue;
      }
    }

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

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

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

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

	public function destroy($id)
	{
    $this->checkAuthorization(auth()->user(), ['forms.other.delete']);
    $role = auth()->user()->getRoleNames()[0];
    
		$form = FormOthers::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 Other (' . $form->expense_number . ')');
    
		$form->delete();

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