<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\View;
use App\Models\User;
use App\Models\Sla;
use App\Models\Severity;
use Illuminate\Http\Request;
use App\Modules\Clients\Client;
use App\Modules\Bookings\Project;
use App\Modules\Bookings\Repair;
use App\Http\Controllers\BaseController;
use App\Modules\Quotes\Quote;

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

    /**
     *	Returns the index page.
     */
    public function getIndex()
    {
        // Fetch the users
        $users = User::with('profile_photo')->get();
        $_users = [null => ''];

        foreach ($users as $key => $value) {
            $_users[$value->id] = $value->name;
        }

        // Load all SLAs
        $sla = Sla::all();
        $_sla = [null => ''];

        foreach ($sla as $s) {
            $_sla[$s['id']] = $s['name'];
        }

        // Fetch the severities
        $severities = Severity::all();
        $_severities = ['' => 'Select severity'];

        foreach ($severities as $key => $s) {
            $_severities[$s['id']] = $s['name'];
        }

        $data = [
            'users'               => $_users,
            'sla_dropdown'        => $_sla,
            'severities_dropdown' => $_severities,
        ];
        // dd($data);
        $this->layout->content = View::make('bookings::index', $data);
    }

    public function getProjectTask(Request $request, $cid, $pid) {

      $users = User::with('profile_photo')->get();
      $_users = [null => ''];

      foreach ($users as $key => $value) {
          $_users[$value->id] = $value->name;
      }

      // Load all SLAs
      $sla = Sla::all();
      $_sla = [null => ''];

      foreach ($sla as $s) {
          $_sla[$s['id']] = $s['name'];
      }

      // Fetch the severities
      $severities = Severity::all();
      $_severities = ['' => 'Select severity'];

      foreach ($severities as $key => $s) {
          $_severities[$s['id']] = $s['name'];
      }

      $client = Client::find($cid);

      if ($client) {
        $_client = $client;
      }

      $project = Project::find($pid);

      if ($project) {
        $_project = $project;
      }

      $data = [
          'users'               => $_users,
          'sla_dropdown'        => $_sla,
          'severities_dropdown' => $_severities,
          'client' => $_client,
          'project' => $_project,
      ];
      // dd($data);
      $this->layout->content = View::make('bookings::index', $data);
    }

    public function getConfirmationSheet($id = '')
    {
        \Log::info("Confirmation Sheet: Method called with ID: {$id}");
        
        // Return an empty page if no ID is passed
        if (! $id) {
            \Log::warning("Confirmation Sheet: No ID provided, returning empty response");
            return '';
        }

        \Log::info("Confirmation Sheet: Attempting to find repair with ID: {$id}");
        
        try {
            // Check if the repair exists first
            $repair = Repair::find($id);
            \Log::info("Confirmation Sheet: Database query completed for ID: {$id}");
            
            if (!$repair) {
                // Log the missing repair for debugging
                \Log::warning("Confirmation sheet requested for non-existent repair ID: {$id}");
                
                // Return a user-friendly error page or redirect
                return response()->view('errors.404', [
                    'message' => "Repair #{$id} not found. This repair may not exist in the system or may have been removed."
                ], 404);
            }

            \Log::info("Confirmation Sheet: Repair found, ID: {$id}, Type: {$repair->type}");

            // Load devices relationship safely
            \Log::info("Confirmation Sheet: Loading devices relationship for repair ID: {$id}");
            $repair->load('devices');
            \Log::info("Confirmation Sheet: Devices loaded successfully, count: " . $repair->devices->count());

        } catch (\Exception $e) {
            \Log::error("Confirmation Sheet: Database error for ID {$id}: " . $e->getMessage());
            \Log::error("Confirmation Sheet: Stack trace: " . $e->getTraceAsString());
            
            return response()->view('errors.500', [
                'message' => "Database error occurred while loading repair #{$id}"
            ], 500);
        }

        try {
            \Log::info("Confirmation Sheet: Attempting to get random quote");
            
            // Get a random quote from the database
            $randomQuote = Quote::getRandomQuote();
            \Log::info("Confirmation Sheet: Quote query completed, result: " . ($randomQuote ? 'found' : 'not found'));
            
            // Fallback to hardcoded quotes if no quotes in database
            if (!$randomQuote) {
                \Log::info("Confirmation Sheet: Using fallback hardcoded quotes");
                $quotes = [];
                $quotes[0] = 'A gem is not polished without rubbing, nor a man perfected without trials';
                $quotes[1] = "A child's life is like a piece of paper on which every person leaves a mark.";
                $quotes[2] = 'He who asks is a fool for five minutes, but he who does not ask remains a fool forever.';
                $quotes[3] = 'If you are patient in one moment of anger, you will escape a hundred days of sorrow.';
                $quotes[4] = "Do not remove a fly from your friend's forehead with a hatchet.";
                $quotes[5] = "Don't trust an American who runs a computer shop";
                $quotes[6] = 'A drop of water shall be returned with a burst of spring.';
                $quotes[7] = "If the wind comes from an empty cave, it's not without a reason.";
                $quotes[8] = 'There are secrets within lies, answers within riddles. Open your mind and hear what your heart wants to deny.';
                $quotes[9] = 'Mists of dreams drip along the nascent echo and love no more.';
            } else {
                \Log::info("Confirmation Sheet: Using database quote: " . substr($randomQuote->text, 0, 50) . "...");
                $quotes = [$randomQuote->text];
            }

        } catch (\Exception $e) {
            \Log::error("Confirmation Sheet: Quote error for ID {$id}: " . $e->getMessage());
            // Use fallback quotes if Quote model fails
            $quotes = ['A gem is not polished without rubbing, nor a man perfected without trials'];
        }

        try {
            \Log::info("Confirmation Sheet: Preparing data array for view");
            
            $data = [
                'quotes' => $quotes,
                'repair' => $repair,
            ];

            \Log::info("Confirmation Sheet: Attempting to render view 'bookings::confirmation_sheet'");
            
            // Monitor memory usage during view rendering
            $memoryBefore = memory_get_usage(true);
            \Log::info("Confirmation Sheet: Memory before view rendering: " . round($memoryBefore / 1024 / 1024, 2) . " MB");
            
            $result = view('bookings::confirmation_sheet', $data);
            
            $memoryAfter = memory_get_usage(true);
            $memoryUsed = $memoryAfter - $memoryBefore;
            \Log::info("Confirmation Sheet: Memory after view rendering: " . round($memoryAfter / 1024 / 1024, 2) . " MB (Used: " . round($memoryUsed / 1024 / 1024, 2) . " MB)");
            
            \Log::info("Confirmation Sheet: View rendered successfully for ID: {$id}");
            
            return $result;
            
        } catch (\Exception $e) {
            \Log::error("Confirmation Sheet: View rendering error for ID {$id}: " . $e->getMessage());
            \Log::error("Confirmation Sheet: View error stack trace: " . $e->getTraceAsString());
            
            return response()->view('errors.500', [
                'message' => "View rendering error occurred for repair #{$id}"
            ], 500);
        }
    }
}
