<?php
use Carbon\Carbon;
use App\Models\Sites;
use App\Models\ReportLog;
use App\Models\Notification;
use App\Models\AttendanceLog;
use App\Models\EmpCompanyDetails;
use App\Models\WhsItem;
use App\Models\WhsReportItem;
// use PDF;
// use Exception;
use Illuminate\Support\Facades\DB;
use App\Models\WhsReport;
use App\Models\GeneratedPdfReport;
use Illuminate\Support\Facades\Auth;

if (!function_exists('formatDateTime')) {
    function formatDateTime($time, $format = 'd/m/y H:i')
    {
        if($time){
            $parsed = \App\Models\BaseModel::safeCarbonParse($time, 'formatDateTime');
            if ($parsed instanceof \Carbon\Carbon) {
                return $parsed->format($format);
            }
            return $time; // Return original if parsing fails
        }
    }
}

if (!function_exists('formatDate')) {
    function formatDate($date, $format = 'd/m/y')
    {
        if($date){
            $parsed = \App\Models\BaseModel::safeCarbonParse($date, 'formatDate');
            if ($parsed instanceof \Carbon\Carbon) {
                return $parsed->format($format);
            }
            return $date; // Return original if parsing fails
        }
    }
}

if (!function_exists('formatTime')) {
    function formatTime($time, $format = 'H:i')
    {
        if($time){
            $parsed = \App\Models\BaseModel::safeCarbonParse($time, 'formatTime');
            if ($parsed instanceof \Carbon\Carbon) {
                return $parsed->format($format);
            }
            return $time; // Return original if parsing fails
        }
    }
}

if (!function_exists('getWeekdays')) {
    function getWeekdays()
    {
        $startDate = Carbon::today(); // Get the current date
        $weekdays = [];
        for ($i = 0; $i < 7; $i++) {
            $currentDate = $startDate->copy()->addDays($i);
            $dayName = $currentDate->format('l'); // Get the full day name
            $weekdays[] = $dayName;
        }
        return $weekdays;
    }
}

if (!function_exists('displayFileSize')) {
    function displayFileSize($filename)
    {
        $filePath = public_path($filename);
        if (file_exists($filePath)) {
            $fileSizeInBytes = filesize($filePath);

            $fileSizeInKb = $fileSizeInBytes / 1024; // Kilobytes
            $fileSizeInMb = $fileSizeInBytes / (1024 * 1024); // Megabytes

            return round($fileSizeInMb, 2) . " MB";
        } else {
            return false;
        }
    }
}

if (!function_exists('docSize')) {
    function docSize($filename)
    {
        $firstFilePath = public_path("upload/documents/".$filename);
        $secondFilePath = public_path($filename);

        if (file_exists($firstFilePath)) {
            $fileSizeInBytes = filesize($firstFilePath);
        } elseif (file_exists($secondFilePath)) {
            $fileSizeInBytes = filesize($secondFilePath);
        } else {
            return false; 
        }

        $fileSizeInKb = $fileSizeInBytes / 1024; // Kilobytes
        $fileSizeInMb = $fileSizeInBytes / (1024 * 1024); // Megabytes

        return round($fileSizeInMb, 2) . " MB";
    }
}
if (!function_exists('convertMinutesToHours'))
{
    function convertMinutesToHours($minutes)
    {
        $hours = floor($minutes / 60);
        $remainingMinutes = $minutes % 60;

        return sprintf('%02d', $hours) . "h:" . sprintf('%02d', $remainingMinutes) . "m";

    }
}

if (!function_exists('getDaysBetween'))
{
    function getDaysBetween($startDate, $endDate, $daysOfWeek) {
        $result = [];

        $currentDate = \App\Models\BaseModel::safeCarbonParse($startDate, 'getDaysBetween-startDate');
        $endDateParsed = \App\Models\BaseModel::safeCarbonParse($endDate, 'getDaysBetween-endDate');

        if (!($currentDate instanceof \Carbon\Carbon) || !($endDateParsed instanceof \Carbon\Carbon)) {
            return $result; // Return empty array if parsing fails
        }

        // Convert user's day numbering (1-7 where 7=Sunday) to Carbon's numbering (0-6 where 0=Sunday)
        $carbonDaysOfWeek = array_map(function($day) {
            return $day == 7 ? 0 : $day; // Convert Sunday from 7 to 0
        }, $daysOfWeek);

        while ($currentDate->lte($endDateParsed)) {
            if (in_array($currentDate->dayOfWeek, $carbonDaysOfWeek)) {
                $result[] = $currentDate->format('d-m-Y') . ', ' . $currentDate->format('l');
            }

            $currentDate->addDay(); // Move to the next day
        }

        return $result;
    }
}


if (!function_exists('countNotifications'))
{
    function countNotifications(){
       return $count = Notification::where('receiver_id',Auth::user()->id)->where('read','0')->count();

    }
 }

if (!function_exists('showNotifications'))
{
    function showNotifications() 
    {
      $notifications = Notification::where('receiver_id',Auth::user()->id)->orderBy('id', 'DESC')->get();
      $count = Notification::where('receiver_id',Auth::user()->id)->where('read','0')->get();
      $html = ''; 

      foreach($notifications as $notification)
      {
    
        $bg_color =  $notification->read == 0 ? 'notification_bg_color' : '';
        $img = url('/assets/img/default.png');
        $dateTimeFromDatabase = \App\Models\BaseModel::safeCarbonParse($notification->created_at, 'notification-created_at');
        $ago = str_replace("after","",$dateTimeFromDatabase->diffForHumans(Carbon::now()));
        $ago = str_replace("before","",$ago);

        $html .= '
        <li class="list-group-item list-group-item-action dropdown-notifications-item '.$bg_color.'" style="width:380px;min-height: 80px;">
            <div class="d-flex align-items-center gap-2">
            <div class="flex-shrink-0">
                <div class="avatar me-1">
                <img src="'.$img.'" class="w-px-40 h-auto rounded-circle">
                </div>
            </div>
            <div class="d-flex flex-column flex-grow-1 overflow-hidden w-px-250">
                <h6 class="mb-1">'.$notification->title.'</h6>
                <small class="text-body">'.$notification->short_description.'</small>
            </div>
            <div class="flex-shrink-0 dropdown-notifications-actions">
                <small class="text-muted">'.$ago.' ago</small>
            </div>
            </div>
        </li>';
      }

      if($html == '')
      {
        $html = '
        <li class="list-group-item list-group-item-action dropdown-notifications-item" style="width:380px;">
            <div class="" style="text-align: center !important;">
                 No notifications yet
            </div>
        </li>
        ';
      }
      return $html;
      
    }
}

if (!function_exists('storeAttendanceLogs'))
{
    function storeAttendanceLogs($logs) {
        AttendanceLog::create([
            'employee_id' => $logs['employee_id'],
            'site_id' => $logs['site_id'],
            'check_in' => $logs['check_in'],
            'check_out' => $logs['check_out'],
            'date' => $logs['date'],
            'longitude' => $logs['longitude'],
            'latitude' => $logs['latitude'],
            'message' => $logs['message'],
            'error_type' => $logs['error_type'],
            'request_type' => $logs['request_type'],
            'customer_id' => $logs['customer_id'] ?? 0,
            'workspace_id' => $logs['workspace_id'] ?? 0,
        ]);
    }
}
if (!function_exists('storeReportsLogs'))
{
    function storeReportsLogs($logs) {
        ReportLog::create([
            'employee_id' => $logs['employee_id'],
            'report_id' => $logs['report_id'] ?? 0,
            'message' => $logs['message'],
            'report_type' => $logs['report_type'] ?? 'general',
            'error_type'=>$logs['error_type']??'success'
        ]);
    }
}
if (!function_exists('storeWHSReportsLogs'))
{
    function storeWHSReportsLogs($logs) {
        ReportLog::create([
            'employee_id' => $logs['employee_id'],
            'report_id' => $logs['report_id'] ?? 0,
            'message' => $logs['message'],
            'report_type' => $logs['report_type'] ?? 'whs_report',
        ]);
    }
}
if (!function_exists('sitesList'))
{
    function sitesList()
    {
        return Sites::where('active',1)->where('del',0)->select('id','title','longitude','latitude','area_radius')->get();
    }
}

if (!function_exists('authUserData'))
{
    function authUserData()
    {
        return EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id',Auth::user()->id)->select('id','employee_email')->first();
    }
}

if (!function_exists('formatHours'))
{
    function formatHours($time24)
    {
        return Carbon::createFromFormat('H:i:s', $time24)->format('h:i A');
    }
}

if(!function_exists('getUsersList')){

    function getUsersList(){
        $emp_list = EmpCompanyDetails::
            with(
                [
                    'empPersonalDetails' => function ($query) {
                        $query->select('emp_id', 'first_name', 'middle_name', 'last_name');
                    },
                    'accessRole' => function ($query) {
                        $query->select('id', 'title', 'code');
                    },
                    'empTier' => function ($query) {
                        $query->select('id', 'title');
                    },
                ]
            )
            ->select('id', 'access_role', 'tier_id')
            ->get();
        if(!$emp_list){
            return [];
        }
        return $emp_list;
}
}



if (!function_exists('whsReportDownloadPdf'))
{
    function whsReportDownloadPdf($ids)
    {
        if (!$ids) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Download ID is required :' ,
                'report_id' => 0,
                'report_type' => 'whs_report'
            ];  
            storeReportsLogs($log);
             return response()->json([
                 'message' => 'Report ID is Required.'
             ], 422);
         }
        try {
            $whs_data = DB::table('whs_reports')
            ->leftJoin('emp_personal_details as authorised_by', 'whs_reports.authorised_by', '=', 'authorised_by.id')
            ->leftJoin('projects as projects', 'whs_reports.project_id', '=', 'projects.id')
            ->leftJoin('swms as swms', 'whs_reports.swms_id', '=', 'swms.id')
            ->where('whs_reports.id', "=", $ids)
            ->select(
                'whs_reports.*',
                'projects.title as project_title',
                'swms.title as swms_title',
                'swms.swms_number as swms_number',
                'swms.revision_number as swms_revision_number',
                'swms.version_number as version_number',
                'authorised_by.first_name as authorised_by_first_name',
                'authorised_by.last_name as authorised_by_or_forman_last_name',)
            ->first();
    
    
             $positions_responsible = DB::table('whs_responsible')
            ->Join('roles', 'whs_responsible.role_id', '=', 'roles.id')
            ->where('whs_responsible.whs_report_id', "=", $ids)
            ->select(
                'roles.*',)
            ->get();
    
             $personal_attending = DB::table('whs_additional_persons')
            ->Join('emp_personal_details', 'whs_additional_persons.employee_id', '=', 'emp_personal_details.id')
            ->where('whs_additional_persons.whs_report_id', "=", $ids)
            ->select(
                'emp_personal_details.*',)
            ->get();
              
            $whs_conducted_by = DB::table('whs_conducted_by')
            ->Join('emp_personal_details', 'whs_conducted_by.employee_id', '=', 'emp_personal_details.id')
            ->where('whs_conducted_by.whs_report_id', "=", $ids)
            ->select(
                'emp_personal_details.*',)
            ->get();
    
    
            $whs_item = DB::table('whs_items')
                        ->where('status', 1)
                        ->get();
    
            $whsReportItems = WhsReportItem::where('whs_report_id', $ids)->get()->keyBy('whs_items_id')->map(function ($item) {
            return $item->values;
            }); 
    
             $whs_hazards = DB::table('whs_report_hazards')
            ->Join('roles', 'whs_report_hazards.role_id', '=', 'roles.id')
            ->where('whs_report_hazards.whs_report_id', "=", $ids)
            ->select(
               'whs_report_hazards.*',
                    'roles.title as role_title',)
            ->get();
            
            $report_images = DB::table('whs_images')
            ->where('whs_report_id', $ids)
            ->get();
           
             $viewPath = 'WHSreport.NewWHSreport.PdfReport.whsReport';
             $html = view($viewPath, compact(
               
                 'whs_data',
                 'positions_responsible',
                 'personal_attending',
                 'whs_conducted_by',
                 'whs_item',
                 'whsReportItems',
                 'whs_hazards',
                 'report_images',

             ))->render();

            $report_whs_number =$whs_data->number??'NO WHS';
            $report_title=$whs_data->title??'No named';
            $report_whs_revision=$whs_data->revision_number??'No Revision'; 
            $filename =  $report_title."N". $report_whs_number."R".$report_whs_revision. ".pdf";

            // $filename = "WHS-REPORT-1-" . $ids . ".pdf";
            $path = public_path("Files_manager/whs_reports/{$filename}");
            $report_full_path = public_path('Files_manager/whs_reports/' . $filename);
            $already_file_status = GeneratedPdfReport::where('report_type','whs_report')->where('report_id', $ids)->where('path', url('Files_manager/whs_reports/' . $filename))->first();
            if (file_exists($report_full_path) && $already_file_status && $already_file_status->path == url('Files_manager/whs_reports/' . $filename)) {
                
                return response()->download($report_full_path, $filename);
            }


            $pdf = PDF::loadHTML($html)
                ->setPaper('A4', 'portrait');
            $pdf->save($path);
            $generated_report=new GeneratedPdfReport();
            $generated_report->report_id=$ids;
            $generated_report->path = url('Files_manager/whs_reports/'.$filename);
            $generated_report->report_type='whs_report';
            $generated_report->save();
           
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS PDF download Successfully:' ,
                'report_id' =>  $ids,
                'report_type' => 'whs_report'
            ];  
             storeReportsLogs($log);
             return response()->download($path, $filename);
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS step download error:'.$shortMessage ,
                'report_id' =>  $ids,
                'report_type' => 'whs_report'
            ];  
             storeReportsLogs($log);
            return response()->json([
                'message' => 'An error occurred : ' . $shortMessage,
            ], 500);
        }
    }
}

if (!function_exists('getCompanyEmailDetails')) {
    /**
     * Get company email details based on authenticated user
     * This is a global helper function that can be called directly from blade templates
     */
    function getCompanyEmailDetails()
    {
        try {
            return \App\Services\CompanyEmailDetails::getCompanyEmailDetails();
        } catch (\Exception $e) {
            // Fallback to basic defaults if service fails
            return [
                'logoPath' => null,
                'companyName' => env('APP_NAME', 'WMS'),
                'companyAddress' => '',
                'companyCity' => '',
                'companyState' => '',
                'companyPostCode' => '',
                'companyCountry' => '',
                'companyPhone' => 'Contact Information',
                'companyEmail' => env('EMAIL_ADDRESS', 'support@example.com'),
            ];
        }
    }
}