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

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

// Define base path correctly for pos/shifts subdirectory
// Current file: /HMSPOS/pos/shifts/close.php
// BASE_PATH should be: /HMSPOS/
if (!defined('BASE_PATH')) {
    // Go up 2 levels: from shifts/ to pos/ to HMSPOS/
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

// Debug - can be removed after confirming it works
error_log("Close Shift - BASE_PATH: " . BASE_PATH);
error_log("Close Shift - Current file: " . __FILE__);
error_log("Close Shift - Shift ID: " . ($_GET['id'] ?? 'none'));

// Load required files with error checking
$required_files = [
    '/config/config.php',
    '/config/database.php',
    '/config/auth.php'
];

foreach ($required_files as $file) {
    $full_path = BASE_PATH . $file;
    if (file_exists($full_path)) {
        require_once $full_path;
    } else {
        // Try alternative path
        $alt_path = dirname(BASE_PATH) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            die("Critical error: Required file not found at: " . $full_path);
        }
    }
}

// Load optional files
if (file_exists(BASE_PATH . '/config/constants.php')) {
    require_once BASE_PATH . '/config/constants.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
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.shifts.manage');
// }

// Set page title
$page_title = 'Close Shift';

// 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 shift ID from URL
$shift_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$shift = null;

try {
    if (!$shift_id) {
        // Get current open shift for this user
        $shift = db_fetch_one("
            SELECT s.*, o.outlet_name
            FROM pos_shifts s
            LEFT JOIN pos_outlets o ON s.outlet_id = o.outlet_id
            WHERE s.user_id = ? AND s.status = 'open'
            ORDER BY s.opened_at DESC LIMIT 1
        ", [$user_id]);
        
        if (!$shift) {
            if (function_exists('set_flash_message')) {
                set_flash_message('warning', 'No open shift found');
            }
            if (function_exists('redirect')) {
                redirect('open.php');
            } else {
                header('Location: open.php');
                exit;
            }
        }
        
        $shift_id = $shift['shift_id'];
    } else {
        // Get specific shift
        $shift = db_fetch_one("
            SELECT s.*, o.outlet_name
            FROM pos_shifts s
            LEFT JOIN pos_outlets o ON s.outlet_id = o.outlet_id
            WHERE s.shift_id = ?
        ", [$shift_id]);
        
        if (!$shift) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'Shift not found');
            }
            if (function_exists('redirect')) {
                redirect('../dashboard.php');
            } else {
                header('Location: ../dashboard.php');
                exit;
            }
        }
        
        // Check if user can close this shift
        if ($shift['user_id'] != $user_id) {
            if (function_exists('set_flash_message')) {
                set_flash_message('danger', 'You can only close your own shifts');
            }
            if (function_exists('redirect')) {
                redirect('../dashboard.php');
            } else {
                header('Location: ../dashboard.php');
                exit;
            }
        }
    }
} catch (Exception $e) {
    error_log("Error fetching shift: " . $e->getMessage());
    die("Error loading shift information. Please try again.");
}

// Get shift sales summary
$sales_summary = [];
$totals = [
    'cash' => 0,
    'card' => 0,
    'mobile' => 0,
    'room_charge' => 0,
    'total' => 0,
    'refunds' => 0
];

try {
    $sales_summary = db_fetch_all("
        SELECT 
            s.payment_method,
            COUNT(*) as transaction_count,
            COALESCE(SUM(s.total_amount), 0) as total
        FROM pos_sales s
        WHERE s.shift_id = ? AND s.payment_status = 'completed'
        GROUP BY s.payment_method
    ", [$shift_id]) ?: [];

    foreach ($sales_summary as $sale) {
        $method = strtolower($sale['payment_method'] ?? '');
        if (strpos($method, 'cash') !== false) {
            $totals['cash'] += $sale['total'];
        } elseif (strpos($method, 'card') !== false) {
            $totals['card'] += $sale['total'];
        } elseif (strpos($method, 'mobile') !== false) {
            $totals['mobile'] += $sale['total'];
        } elseif (strpos($method, 'room') !== false) {
            $totals['room_charge'] += $sale['total'];
        }
        $totals['total'] += $sale['total'];
    }
} catch (Exception $e) {
    error_log("Error fetching sales summary: " . $e->getMessage());
}

// Get recent transactions for this shift
$recent_sales = [];
try {
    $recent_sales = db_fetch_all("
        SELECT s.*
        FROM pos_sales s
        WHERE s.shift_id = ?
        ORDER BY s.sale_time DESC
        LIMIT 20
    ", [$shift_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching recent sales: " . $e->getMessage());
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'close') {
            $closing_cash = (float)($_POST['closing_cash'] ?? 0);
            $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
            
            if ($closing_cash < 0) {
                $errors[] = 'Closing cash cannot be negative';
            }
            
            if (empty($errors)) {
                try {
                    if (function_exists('begin_transaction')) {
                        begin_transaction();
                    }
                    
                    $expected_cash = ($shift['opening_cash'] ?? 0) + $totals['cash'] - $totals['refunds'];
                    
                    $update_data = [
                        'closed_at' => date('Y-m-d H:i:s'),
                        'closing_cash' => $closing_cash,
                        'expected_cash' => $expected_cash,
                        'cash_sales' => $totals['cash'],
                        'card_sales' => $totals['card'],
                        'mobile_sales' => $totals['mobile'],
                        'room_charge_sales' => $totals['room_charge'],
                        'total_sales' => $totals['total'],
                        'status' => 'closed'
                    ];
                    
                    if (!empty($notes)) {
                        $update_data['notes'] = $notes;
                    }
                    
                    if (function_exists('db_update')) {
                        db_update('pos_shifts', $update_data, 'shift_id = ?', [$shift_id]);
                    } else {
                        // Fallback direct update
                        $pdo = get_db_connection();
                        $sql = "UPDATE pos_shifts SET 
                                closed_at = ?, closing_cash = ?, expected_cash = ?,
                                cash_sales = ?, card_sales = ?, mobile_sales = ?,
                                room_charge_sales = ?, total_sales = ?, status = ?
                                WHERE shift_id = ?";
                        $stmt = $pdo->prepare($sql);
                        $stmt->execute([
                            date('Y-m-d H:i:s'),
                            $closing_cash,
                            $expected_cash,
                            $totals['cash'],
                            $totals['card'],
                            $totals['mobile'],
                            $totals['room_charge'],
                            $totals['total'],
                            'closed',
                            $shift_id
                        ]);
                    }
                    
                    // Audit log
                    if (function_exists('audit_log')) {
                        audit_log($user_id, 'close_shift', 'pos_shifts', $shift_id, 
                                 ['status' => 'open'], 
                                 ['status' => 'closed', 'expected' => $expected_cash, 'actual' => $closing_cash]);
                    }
                    
                    if (function_exists('commit_transaction')) {
                        commit_transaction();
                    }
                    
                    if (function_exists('set_flash_message')) {
                        set_flash_message('success', 'Shift closed successfully');
                    }
                    
                    // Redirect to reconciliation page
                    if (function_exists('redirect')) {
                        redirect('reconciliation.php?id=' . $shift_id);
                    } else {
                        header('Location: reconciliation.php?id=' . $shift_id);
                        exit;
                    }
                    
                } catch (Exception $e) {
                    if (function_exists('rollback_transaction')) {
                        rollback_transaction();
                    }
                    $errors[] = 'Failed to close shift: ' . $e->getMessage();
                    if (function_exists('log_message')) {
                        log_message("Close shift failed: " . $e->getMessage(), 'ERROR');
                    } else {
                        error_log("Close shift failed: " . $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>Close POS Shift</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">
        <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="#">Close POS Shift</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">Close Shift</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/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/shifts/index.php">Shifts</a></li>
                    <li class="breadcrumb-item active">Close Shift</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Error Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Shift Information -->
            <div class="col-md-4">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock mr-1"></i>
                            Shift Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Shift Code:</th>
                                <td><strong><?php echo htmlspecialchars($shift['shift_code'] ?? 'N/A'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Outlet:</th>
                                <td><?php echo htmlspecialchars($shift['outlet_name'] ?? 'N/A'); ?></td>
                            </tr>
                            <tr>
                                <th>Opened:</th>
                                <td><?php echo isset($shift['opened_at']) ? date('Y-m-d H:i', strtotime($shift['opened_at'])) : 'N/A'; ?></td>
                            </tr>
                            <tr>
                                <th>Duration:</th>
                                <td>
                                    <?php 
                                    if (isset($shift['opened_at'])) {
                                        $opened = new DateTime($shift['opened_at']);
                                        $now = new DateTime();
                                        $interval = $opened->diff($now);
                                        echo $interval->format('%h hours %i minutes');
                                    } else {
                                        echo 'N/A';
                                    }
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Opening Cash:</th>
                                <td><?php echo function_exists('format_currency') ? format_currency($shift['opening_cash'] ?? 0) : 'RWF ' . number_format($shift['opening_cash'] ?? 0); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Sales Summary -->
            <div class="col-md-8">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Sales Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <th>Cash Sales:</th>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($totals['cash']) : 'RWF ' . number_format($totals['cash']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Card Sales:</th>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($totals['card']) : 'RWF ' . number_format($totals['card']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Mobile Money:</th>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($totals['mobile']) : 'RWF ' . number_format($totals['mobile']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Room Charges:</th>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($totals['room_charge']) : 'RWF ' . number_format($totals['room_charge']); ?></td>
                                    </tr>
                                    <tr class="table-active">
                                        <th>Total Sales:</th>
                                        <td class="text-right"><strong><?php echo function_exists('format_currency') ? format_currency($totals['total']) : 'RWF ' . number_format($totals['total']); ?></strong></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <th>Opening Cash:</th>
                                        <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($shift['opening_cash'] ?? 0) : 'RWF ' . number_format($shift['opening_cash'] ?? 0); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Cash Sales:</th>
                                        <td class="text-right">+ <?php echo function_exists('format_currency') ? format_currency($totals['cash']) : 'RWF ' . number_format($totals['cash']); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Refunds:</th>
                                        <td class="text-right text-danger">- <?php echo function_exists('format_currency') ? format_currency($totals['refunds']) : 'RWF ' . number_format($totals['refunds']); ?></td>
                                    </tr>
                                    <tr class="table-info">
                                        <th>Expected Cash:</th>
                                        <td class="text-right">
                                            <strong id="expected_cash_display">
                                                <?php 
                                                $expected_cash = ($shift['opening_cash'] ?? 0) + $totals['cash'] - $totals['refunds'];
                                                echo function_exists('format_currency') ? format_currency($expected_cash) : 'RWF ' . number_format($expected_cash);
                                                ?>
                                            </strong>
                                            <input type="hidden" id="expected_cash" value="<?php echo $expected_cash; ?>">
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Close Shift Form -->
        <div class="row">
            <div class="col-md-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-stop mr-1"></i>
                            Close Shift
                        </h3>
                    </div>
                    
                    <form method="POST" id="closeShiftForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="close">
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="actual_cash">Counted Cash</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            </div>
                                            <input type="number" class="form-control" id="actual_cash" name="actual_cash"
                                                   step="0.01" min="0" required>
                                        </div>
                                        <small class="text-muted">Actual cash counted in register</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="difference">Difference</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            </div>
                                            <input type="text" class="form-control" id="difference" readonly>
                                        </div>
                                        <small class="text-muted" id="difference_message"></small>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="closing_cash">Closing Cash</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            </div>
                                            <input type="number" class="form-control" id="closing_cash" name="closing_cash" 
                                                   step="0.01" min="0" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="notes">Shift Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"><?php echo htmlspecialchars($shift['notes'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle mr-2"></i>
                                <strong>Important:</strong> Once closed, you cannot add more transactions to this shift.
                                Make sure all sales are completed and cash is counted correctly.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-stop mr-1"></i> Close Shift
                            </button>
                            <a href="/HMSPOS/pos/dashboard.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list mr-1"></i>
                            Recent Transactions
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($recent_sales)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-receipt fa-3x mb-3"></i>
                                <p>No transactions for this shift</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Time</th>
                                            <th>Receipt</th>
                                            <th>Payment Method</th>
                                            <th class="text-right">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_sales as $sale): ?>
                                        <tr>
                                            <td><?php echo isset($sale['sale_time']) ? date('H:i', strtotime($sale['sale_time'])) : 'N/A'; ?></td>
                                            <td>
                                                <a href="/HMSPOS/pos/sales/receipt.php?id=<?php echo $sale['sale_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($sale['receipt_number'] ?? 'N/A'); ?>
                                                </a>
                                            </td>
                                            <td><?php echo htmlspecialchars($sale['payment_method'] ?? 'N/A'); ?></td>
                                            <td class="text-right"><?php echo function_exists('format_currency') ? format_currency($sale['total_amount'] ?? 0) : 'RWF ' . number_format($sale['total_amount'] ?? 0); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

<script>
$(document).ready(function() {
    // Calculate difference
    function calculateDifference() {
        const expected = parseFloat($('#expected_cash').val()) || 0;
        const actual = parseFloat($('#actual_cash').val()) || 0;
        const difference = actual - expected;
        
        $('#difference').val(difference.toFixed(2));
        $('#closing_cash').val(actual.toFixed(2));
        
        const messageEl = $('#difference_message');
        if (Math.abs(difference) < 0.01) {
            messageEl.html('<span class="text-success">Perfect match ✓</span>');
        } else if (difference > 0) {
            messageEl.html('<span class="text-warning">⚠️ Over by ' + formatCurrency(difference) + '</span>');
        } else {
            messageEl.html('<span class="text-danger">⚠️ Short by ' + formatCurrency(Math.abs(difference)) + '</span>');
        }
    }
    
    $('#actual_cash').on('input', calculateDifference);
    
    function formatCurrency(amount) {
        return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?> ' + amount.toFixed(2);
    }
    
    // Form validation
    $('#closeShiftForm').on('submit', function(e) {
        const actual = parseFloat($('#actual_cash').val());
        
        if (isNaN(actual) || actual < 0) {
            e.preventDefault();
            alert('Please enter the counted cash amount');
            return false;
        }
        
        return confirm('Close this shift? Make sure all cash has been counted and all transactions are complete.');
    });
});
</script>

<style>
.mr-1 { margin-right: 0.25rem; }
.mr-2 { margin-right: 0.5rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.mb-2 { margin-bottom: 0.5rem; }
.text-success { color: #28a745; }
.text-warning { color: #ffc107; }
.text-danger { color: #dc3545; }
.table-sm td, .table-sm th { padding: 0.3rem; }
</style>

<?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>';
}
?>