<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Availability Calendar - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/rooms/availability/calendar.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/availability/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('rates.view');
// }

// Set page title
$page_title = 'Availability Calendar';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get month and year from request
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Validate month and year
if ($month < 1 || $month > 12) $month = (int)date('m');
if ($year < 2020 || $year > 2030) $year = (int)date('Y');

// Calculate previous and next month
$prev_month = $month == 1 ? 12 : $month - 1;
$prev_year = $month == 1 ? $year - 1 : $year;
$next_month = $month == 12 ? 1 : $month + 1;
$next_year = $month == 12 ? $year + 1 : $year;

// Get first day of month and number of days
$first_day = mktime(0, 0, 0, $month, 1, $year);
$days_in_month = (int)date('t', $first_day);
$month_name = date('F Y', $first_day);

// Get starting day of week (0 = Sunday, 6 = Saturday)
$start_weekday = (int)date('w', $first_day);

// Get room types
$room_types = [];
try {
    $room_types = db_fetch_all("
        SELECT rt.*, 
               COUNT(r.room_id) as total_rooms
        FROM room_types rt
        LEFT JOIN rooms r ON rt.room_type_id = r.room_type_id AND r.is_active = 1
        GROUP BY rt.room_type_id
        ORDER BY rt.type_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
    $room_types = [];
}

// Get reservations for the month
$reservations = [];
try {
    $reservations = db_fetch_all("
        SELECT 
            r.reservation_id,
            r.booking_code,
            r.room_type_id,
            r.room_id,
            r.check_in_date,
            r.check_out_date,
            r.booking_status,
            r.adults,
            r.children,
            g.first_name,
            g.last_name,
            rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        LEFT JOIN rooms rm ON r.room_id = rm.room_id
        WHERE (r.check_in_date BETWEEN ? AND ? OR r.check_out_date BETWEEN ? AND ?)
        AND r.booking_status IN ('confirmed', 'checked_in')
        ORDER BY r.check_in_date
    ", [
        "$year-$month-01", 
        date('Y-m-t', strtotime("$year-$month-01")),
        "$year-$month-01", 
        date('Y-m-t', strtotime("$year-$month-01"))
    ]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching reservations: " . $e->getMessage());
    $reservations = [];
}

// Organize reservations by date and room type
$bookings_by_date = [];
foreach ($reservations as $res) {
    if (empty($res['check_in_date']) || empty($res['check_out_date'])) continue;
    
    try {
        $check_in = new DateTime($res['check_in_date']);
        $check_out = new DateTime($res['check_out_date']);
        $period = new DatePeriod($check_in, new DateInterval('P1D'), $check_out);
        
        foreach ($period as $date) {
            $date_str = $date->format('Y-m-d');
            if (!isset($bookings_by_date[$date_str])) {
                $bookings_by_date[$date_str] = [];
            }
            $type_id = $res['room_type_id'] ?? 0;
            if (!isset($bookings_by_date[$date_str][$type_id])) {
                $bookings_by_date[$date_str][$type_id] = [
                    'count' => 0,
                    'bookings' => []
                ];
            }
            $bookings_by_date[$date_str][$type_id]['count']++;
            $bookings_by_date[$date_str][$type_id]['bookings'][] = $res;
        }
    } catch (Exception $e) {
        error_log("Error processing reservation dates: " . $e->getMessage());
    }
}

// Get maintenance and blocked rooms
$maintenance = [];
try {
    $maintenance = db_fetch_all("
        SELECT 
            m.ticket_id,
            m.room_id,
            m.description,
            m.created_at as start_date,
            m.resolved_at as end_date,
            r.room_number,
            rt.room_type_id
        FROM maintenance_tickets m
        JOIN rooms r ON m.room_id = r.room_id
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        WHERE m.status IN ('open', 'in_progress')
        AND (m.created_at BETWEEN ? AND ? OR m.resolved_at BETWEEN ? AND ?)
    ", [
        "$year-$month-01", 
        date('Y-m-t', strtotime("$year-$month-01")),
        "$year-$month-01", 
        date('Y-m-t', strtotime("$year-$month-01"))
    ]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching maintenance: " . $e->getMessage());
    $maintenance = [];
}

$maintenance_by_date = [];
foreach ($maintenance as $m) {
    try {
        $start = new DateTime($m['start_date'] ?? 'now');
        $end = !empty($m['end_date']) ? new DateTime($m['end_date']) : new DateTime('+1 month');
        $period = new DatePeriod($start, new DateInterval('P1D'), $end);
        
        foreach ($period as $date) {
            $date_str = $date->format('Y-m-d');
            if (!isset($maintenance_by_date[$date_str])) {
                $maintenance_by_date[$date_str] = [];
            }
            $type_id = $m['room_type_id'] ?? 0;
            $maintenance_by_date[$date_str][$type_id] = ($maintenance_by_date[$date_str][$type_id] ?? 0) + 1;
        }
    } catch (Exception $e) {
        error_log("Error processing maintenance dates: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Availability Calendar</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Availability Calendar</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Availability Calendar</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/rates/index.php">Rates</a></li>
                    <li class="breadcrumb-item active">Calendar</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Month Navigation -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-body text-center">
                        <div class="btn-group">
                            <a href="?month=<?php echo $prev_month; ?>&year=<?php echo $prev_year; ?>" class="btn btn-primary">
                                <i class="fas fa-chevron-left"></i> Previous Month
                            </a>
                            <a href="?month=<?php echo date('m'); ?>&year=<?php echo date('Y'); ?>" class="btn btn-info">
                                <i class="fas fa-calendar-alt me-1"></i> Current Month
                            </a>
                            <a href="?month=<?php echo $next_month; ?>&year=<?php echo $next_year; ?>" class="btn btn-primary">
                                Next Month <i class="fas fa-chevron-right"></i>
                            </a>
                        </div>
                        <h3 class="mt-3 mb-0"><?php echo $month_name; ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- Legend -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-body py-2">
                        <span class="me-3">
                            <span class="badge bg-success">●</span> Available
                        </span>
                        <span class="me-3">
                            <span class="badge bg-danger">●</span> Fully Booked
                        </span>
                        <span class="me-3">
                            <span class="badge bg-warning">●</span> Partially Available
                        </span>
                        <span class="me-3">
                            <span class="badge bg-info">●</span> Maintenance
                        </span>
                        <span class="me-3">
                            <i class="fas fa-bed text-primary"></i> Occupied
                        </span>
                        <span class="me-3">
                            <i class="fas fa-wrench text-warning"></i> Maintenance
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Calendar -->
        <div class="calendar-container">
            <div class="calendar-grid">
                <!-- Room Type Headers -->
                <div class="calendar-row header-row">
                    <div class="calendar-cell header-cell date-cell">Date</div>
                    <?php foreach ($room_types as $type): ?>
                        <div class="calendar-cell header-cell room-type-cell" title="<?php echo escape_html($type['type_name'] ?? ''); ?>">
                            <strong><?php echo escape_html($type['type_code'] ?? ''); ?></strong>
                            <br>
                            <small><?php echo $type['total_rooms'] ?? 0; ?> rooms</small>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Calendar Days -->
                <?php for ($day = 1; $day <= $days_in_month; $day++): 
                    $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
                    $day_name = date('D', strtotime($date));
                    $is_weekend = in_array($day_name, ['Sat', 'Sun']);
                    $is_today = ($date == date('Y-m-d'));
                ?>
                    <div class="calendar-row <?php echo $is_weekend ? 'weekend-row' : ''; ?> <?php echo $is_today ? 'today-row' : ''; ?>">
                        <!-- Date Cell -->
                        <div class="calendar-cell date-cell">
                            <div class="date-display">
                                <span class="day-number"><?php echo $day; ?></span>
                                <span class="day-name"><?php echo $day_name; ?></span>
                            </div>
                        </div>

                        <!-- Room Type Cells -->
                        <?php foreach ($room_types as $type): 
                            $type_id = $type['room_type_id'] ?? 0;
                            $total_rooms = (int)($type['total_rooms'] ?? 0);
                            $booked = (int)($bookings_by_date[$date][$type_id]['count'] ?? 0);
                            $maintenance_count = (int)($maintenance_by_date[$date][$type_id] ?? 0);
                            $available = $total_rooms - $booked - $maintenance_count;
                            
                            // Determine status class
                            if ($maintenance_count > 0) {
                                $status_class = 'maintenance';
                            } elseif ($available <= 0) {
                                $status_class = 'fully-booked';
                            } elseif ($available < $total_rooms) {
                                $status_class = 'partial';
                            } else {
                                $status_class = 'available';
                            }
                            
                            // Get bookings for this date/type
                            $day_bookings = $bookings_by_date[$date][$type_id]['bookings'] ?? [];
                        ?>
                            <div class="calendar-cell room-cell <?php echo $status_class; ?>"
                                 onclick="showDetails('<?php echo $date; ?>', <?php echo $type_id; ?>)">
                                
                                <!-- Availability Numbers -->
                                <div class="availability-numbers">
                                    <span class="available"><?php echo max(0, $available); ?></span>
                                    <span class="total">/<?php echo $total_rooms; ?></span>
                                </div>
                                
                                <!-- Icons for bookings/maintenance -->
                                <div class="cell-icons">
                                    <?php if ($booked > 0): ?>
                                        <span class="badge bg-primary" title="<?php echo $booked; ?> booked">
                                            <i class="fas fa-bed"></i> <?php echo $booked; ?>
                                        </span>
                                    <?php endif; ?>
                                    
                                    <?php if ($maintenance_count > 0): ?>
                                        <span class="badge bg-warning" title="<?php echo $maintenance_count; ?> maintenance">
                                            <i class="fas fa-wrench"></i> <?php echo $maintenance_count; ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Tooltip with booking details -->
                                <?php if (!empty($day_bookings)): ?>
                                    <div class="cell-tooltip">
                                        <?php foreach (array_slice($day_bookings, 0, 3) as $booking): ?>
                                            <div>
                                                <i class="fas fa-user"></i> <?php echo escape_html($booking['first_name'] ?? ''); ?>
                                                <?php if (!empty($booking['room_number'])): ?>
                                                    <br><small>Room <?php echo escape_html($booking['room_number']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                            <?php if ($booking !== end($day_bookings)): ?><hr class="my-1"><?php endif; ?>
                                        <?php endforeach; ?>
                                        <?php if (count($day_bookings) > 3): ?>
                                            <div class="text-center mt-1">+<?php echo count($day_bookings) - 3; ?> more</div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endfor; ?>
            </div>
        </div>

        <!-- Summary Stats -->
        <div class="row mt-4">
            <?php
            // Calculate stats
            $total_available_sum = 0;
            $total_days_count = 0;
            $total_booked_count = 0;
            $maintenance_days_count = 0;
            
            foreach ($room_types as $type) {
                $type_id = $type['room_type_id'] ?? 0;
                $total_rooms = (int)($type['total_rooms'] ?? 0);
                
                for ($day = 1; $day <= $days_in_month; $day++) {
                    $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
                    $booked = (int)($bookings_by_date[$date][$type_id]['count'] ?? 0);
                    $maintenance_day_count = (int)($maintenance_by_date[$date][$type_id] ?? 0);
                    
                    $total_available_sum += $total_rooms - $booked - $maintenance_day_count;
                    $total_days_count++;
                    $total_booked_count += $booked;
                    $maintenance_days_count += $maintenance_day_count;
                }
            }
            
            $total_room_nights = 0;
            foreach ($reservations as $res) {
                if (!empty($res['check_in_date']) && !empty($res['check_out_date'])) {
                    $nights = (strtotime($res['check_out_date']) - strtotime($res['check_in_date'])) / 86400;
                    $total_room_nights += max(0, $nights);
                }
            }
            
            $total_rooms_available = array_sum(array_column($room_types, 'total_rooms')) * $days_in_month;
            $occupancy_rate = $total_rooms_available > 0 ? round(($total_booked_count / $total_rooms_available) * 100, 1) : 0;
            ?>
            
            <div class="col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-door-open"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Avg. Availability</span>
                        <span class="info-box-number">
                            <?php echo round($total_available_sum / max(1, $total_days_count), 1); ?> rooms/day
                        </span>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-bed"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Room Nights</span>
                        <span class="info-box-number"><?php echo round($total_room_nights); ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-warning"><i class="fas fa-wrench"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Maintenance Days</span>
                        <span class="info-box-number"><?php echo $maintenance_days_count; ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-percent"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Occupancy Rate</span>
                        <span class="info-box-number"><?php echo $occupancy_rate; ?>%</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Availability Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="detailsContent">
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Calendar Styles -->
<style>
.calendar-container {
    overflow-x: auto;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.calendar-grid {
    display: table;
    width: 100%;
    min-width: 800px;
}

.calendar-row {
    display: table-row;
}

.calendar-row.header-row {
    background: #f8f9fa;
    font-weight: bold;
}

.calendar-row.weekend-row {
    background-color: #f8f9fc;
}

.calendar-row.today-row {
    background-color: #fff3cd;
}

.calendar-cell {
    display: table-cell;
    padding: 10px;
    border: 1px solid #dee2e6;
    vertical-align: top;
}

.calendar-cell.header-cell {
    text-align: center;
    background: #e9ecef;
    padding: 15px 5px;
}

.calendar-cell.date-cell {
    width: 100px;
    background: #f8f9fa;
    font-weight: bold;
}

.calendar-cell.room-cell {
    width: 120px;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
}

.calendar-cell.room-cell:hover {
    background-color: #e9ecef;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.calendar-cell.room-cell.available {
    background-color: #d4edda;
}

.calendar-cell.room-cell.partial {
    background-color: #fff3cd;
}

.calendar-cell.room-cell.fully-booked {
    background-color: #f8d7da;
}

.calendar-cell.room-cell.maintenance {
    background-color: #d1ecf1;
}

.date-display {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.day-number {
    font-size: 1.5rem;
    font-weight: bold;
    line-height: 1.2;
}

.day-name {
    font-size: 0.85rem;
    color: #6c757d;
}

.availability-numbers {
    text-align: center;
    margin-bottom: 5px;
}

.availability-numbers .available {
    font-size: 1.3rem;
    font-weight: bold;
}

.availability-numbers .total {
    font-size: 0.9rem;
    color: #6c757d;
}

.cell-icons {
    text-align: center;
    min-height: 40px;
}

.cell-icons .badge {
    margin: 2px;
    padding: 3px 6px;
}

.cell-tooltip {
    display: none;
    position: absolute;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    z-index: 1000;
    min-width: 200px;
    font-size: 0.85rem;
    pointer-events: none;
}

.calendar-cell.room-cell:hover .cell-tooltip {
    display: block;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
}

.info-box {
    min-height: 90px;
    margin-bottom: 0;
}

.info-box-icon {
    width: 70px;
    height: 70px;
    line-height: 70px;
    font-size: 2rem;
}

.info-box-content {
    margin-left: 80px;
}

.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.me-3 { margin-right: 1rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.my-1 { margin-top: 0.25rem; margin-bottom: 0.25rem; }

@media print {
    .main-header, .main-sidebar, .btn, .info-box {
        display: none !important;
    }
    .calendar-container {
        box-shadow: none;
    }
}

.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-primary { background-color: #007bff; color: #fff; }
</style>

<!-- Details Modal Script -->
<script>
function showDetails(date, roomTypeId) {
    const modal = new bootstrap.Modal(document.getElementById('detailsModal'));
    modal.show();
    
    $('#detailsContent').html('<div class="text-center"><div class="spinner-border text-primary"></div></div>');
    
    $.get('/HMSPOS/rooms/availability/ajax.php', {
        action: 'get_details',
        date: date,
        room_type_id: roomTypeId
    }, function(response) {
        $('#detailsContent').html(response);
    }).fail(function(xhr) {
        $('#detailsContent').html('<div class="alert alert-danger">Failed to load details: ' + (xhr.status === 404 ? 'AJAX endpoint not found' : 'Server error') + '</div>');
    });
}
</script>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>