<?php

namespace App\Modules\Hr\controllers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
// use Zipper; // Temporarily disabled - package incompatible with Laravel 5.4
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Models\User;
use App\Modules\Hr\UserDetails;
use App\Modules\Hr\TimeLog;

class HrAdminController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    public function getIndex()
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            return Redirect::to('hr');
        }

        $this->layout->content = View::make('hr::admin.index');
    }

    public function getUsers($id)
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            return Redirect::to('hr');
        }

        $user_details = UserDetails::find($id);

        if (! $user_details) {
            // Here we are creating the user on demand if it doesn't exist

            $user_details = UserDetails::create(['user_id' => $id]);
            // We now need to fetch the user from the Database to get all the fields
            $user_details = UserDetails::find($id);
        }

        // Load the user details from 'users' table
        $user_details->load('user');

        // Render the view
        $this->layout->content = View::make('hr::admin.users', compact('user_details'));
    }

    public function getPDF(Request $request, $id)
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            return Redirect::to('hr');
        }

        // Get the period
        $start = $request->input('start', Carbon::now()->day(28)->subMonth()->toDateString());
        $end = $request->input('end', Carbon::now()->day(27)->toDateString());

        $user_details = UserDetails::find($id);
        $user_details->load('user');

        // Fetch the clocking times for the interval $start - $end - MODERNIZED
        $times = TimeLog::query()
                    ->where('user_id', $id)
                    ->whereDate('time', '>=', $start)
                    ->whereDate('time', '<=', $end)
                    ->get();

        $pdf = \PDF::loadView('hr::admin.pdf', compact('user_details', 'times'));

        return $pdf->stream();
    }

    public function getExcel(Request $request, $id)
    {
        // This function requires management access
        if (! Auth::user()->hasPermission('access_hr')) {
            return Redirect::to('hr');
        }

        // Get user details for filename - EXACTLY like Laravel5
        $user = User::find($id);
        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        // Parse user name into first and last name for filename
        $nameParts = explode(' ', trim($user->name));
        $firstName = strtolower($nameParts[0] ?? 'unknown');
        $lastName = strtolower($nameParts[1] ?? 'user');

        // Get a new instance of the Excel Exporter Service from the IoC container - EXACTLY like Laravel5
        $service = App::make('App\Modules\Hr\ExcelExporter');
        
        // Get the export object - use Laravel5 logic (no endOfDay modification)
        $export = $service->exportLaravel5Style($id, $request->input('start'), $request->input('end'));
        
        // Generate filename following the requested pattern: timesheet-userfirstname-userlastname-2025-07-29-204208.xlsx
        $filename = 'timesheet-' . $firstName . '-' . $lastName . '-' . date('Y-m-d-His') . '.xlsx';
        
        // Direct download - HR downloading employee timesheets
        return Excel::download($export, $filename);
    }

    public function postReport(Request $request)
    {
        // Get a list of active users
        $users = User::getActiveList();
        $files = [];
        $emailed = [];

        // Get a new instance of the Excel Exporter Service from the IoC container
        $service = App::make('App\Modules\Hr\ExcelExporter');
        $path = storage_path('excel/hr/reports/'.time());
        $sendEmail = $request->input('send_email');

        foreach ($users as $user) {
            $file = $service->export($user->id, $request->input('start'), $request->input('end'))
                            ->store('xls', $path, true);

            $files[$user->id] = $file;

            if ($sendEmail && $user->email) {
                // Send an email to each user using global SMTP configuration
                try {
                    \App\Seraph\Services\GlobalMailerService::send('hr::templates.mail', [], function ($message) use ($file, $user) {
                        $message->to($user->email);
                        $message->subject('Your timesheet for this month');
                        $message->attach($file['full']);
                    });

                    $emailed[] = $user;
                } catch (Exception $e) {
                    Log::error($e);
                }
            }
        }

        // Check to see if the user asked for an archive file
        $zip = null;
        if ($request->input('download')) {
            // Check if Zipper is available (temporarily disabled due to Laravel 5.4 incompatibility)
            if (class_exists('Zipper')) {
                $zip = 'storage/reports/'.'timesheets-'.date('Y-m-d-His').'.zip';
                Zipper::make(public_path($zip))->add($path)->close();

                // Check to see if the archive was created,
                // otherwise set the variable to null
                if (! File::exists(public_path($zip))) {
                    $zip = null;
                }
            } else {
                // Fallback: provide a message about zip functionality being temporarily unavailable
                Log::warning('Zip functionality temporarily unavailable due to package incompatibility');
            }
        }

        // Delete the folder
        File::deleteDirectory($path);

        return [
            'total_users' => count($users),
            'emailed'     => $emailed,
            'zip'         => $zip ? URL::asset($zip) : null,
            'message'     => !class_exists('Zipper') ? 'Zip download temporarily unavailable' : null,
        ];
    }

    public function postIndividualReport(Request $request, $id)
    {
      // Get user from $id param
      $user = User::find($id);
      $emailed = [];

      // Get a new instance of the Excel Exporter Service from the IoC container
      $service = App::make('App\Modules\Hr\ExcelExporter');
      $path = storage_path('excel/hr/reports/'.time());
      $sendEmail = $request->input('send_email');

      // Create the directory if it doesn't exist
      if (!File::exists($path)) {
          File::makeDirectory($path, 0755, true);
      }

      // Generate filename - sanitize user name to avoid file path issues
      $sanitizedName = preg_replace('/[^A-Za-z0-9\-_]/', '_', trim($user->name));
      $filename = $sanitizedName . '_' . date('Y-m-d_His') . '.xlsx';
      $filepath = $path . '/' . $filename;

      // Get the Excel export object
      $export = $service->export($user->id, $request->input('start'), $request->input('end'));
      
      // Create public storage directory if it doesn't exist
      $publicDir = storage_path('app/public/reports');
      if (!File::exists($publicDir)) {
          File::makeDirectory($publicDir, 0755, true);
      }

      // Store the Excel file directly to public storage using Laravel Excel
      $storedPath = Excel::store($export, 'reports/' . $filename, 'public');
      
      // Clean up temporary directory
      if (File::exists($path)) {
          File::deleteDirectory($path);
      }

      return [
          'total_users' => 1,
          'emailed'     => $emailed,
          'zip'         => url('storage/reports') . '/' . $filename,
      ];
    }
  }
