<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Shift Reconciliation Report
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct base path dynamically using multiple fallbacks
$base_path = null;

// Method 1: Try going up 3 levels from current file
// Current file: /admin/pos/shifts/reconciliation.php
// Target: /config/config.php
$base_path = dirname(__DIR__, 3);

// Method 2: Try with document root
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/HMSPOS';
}

// Method 3: Try one more absolute path for XAMPP
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try with realpath
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = realpath(__DIR__ . '/../../..');
}

// Method 5: Try to find config by traversing up
if (!file_exists($base_path . '/config/config.php')) {
    $current_dir = __DIR__;
    for ($i = 0; $i < 5; $i++) {
        $current_dir = dirname($current_dir);
        if (file_exists($current_dir . '/config/config.php')) {
            $base_path = $current_dir;
            break;
        }
    }
}

// Verify config file exists
if (!file_exists($base_path . '/config/config.php')) {
    die('Critical Error: Cannot locate config.php. Please check file paths.<br>
         Base path tried: ' . $base_path . '<br>
         Current directory: ' . __DIR__ . '<br>
         Document root: ' . ($_SERVER['DOCUMENT_ROOT'] ?? 'Not set'));
}

// Initialize system with error handling
try {
    require_once $base_path . '/config/config.php';
    
    // Check if constants.php exists
    if (file_exists($base_path . '/config/constants.php')) {
        require_once $base_path . '/config/constants.php';
    }
    
    // Check if database.php exists
    if (file_exists($base_path . '/config/database.php')) {
        require_once $base_path . '/config/database.php';
    }
    
    // Check if helpers.php exists
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    
    // Check if auth.php exists
    if (file_exists($base_path . '/config/auth.php')) {
        require_once $base_path . '/config/auth.php';
    }
    
    // Check if csrf.php exists
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
    
} catch (Exception $e) {
    die('Error loading system files: ' . $e->getMessage());
}

// Define constants if not defined
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}

// Define base_url function if not exists
if (!function_exists('base_url')) {
    function base_url($path = '') {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $script_name = $_SERVER['SCRIPT_NAME'];
        $dir = dirname(dirname(dirname($script_name)));
        return $protocol . $host . rtrim($dir, '/') . '/' . ltrim($path, '/');
    }
}

// Define escape_html function if not exists
if (!function_exists('escape_html')) {
    function escape_html($string) {
        return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define format_currency function if not exists
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return CURRENCY_SYMBOL . ' ' . number_format($amount ?? 0, 2);
    }
}

// Define format_datetime function if not exists
if (!function_exists('format_datetime')) {
    function format_datetime($datetime) {
        if (empty($datetime)) return 'N/A';
        return date('d M Y H:i', strtotime($datetime));
    }
}

// Define set_flash_message function if not exists
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION['flash_message'] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if not exists
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . base_url($url));
        exit;
    }
}

// Define csrf_field function if not exists
if (!function_exists('csrf_field')) {
    function csrf_field() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $token = bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Require authentication with error handling
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (!isset($_SESSION['user_id'])) {
        header('Location: ' . base_url('login.php'));
        exit;
    }
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('pos.shifts.manage');
} elseif (function_exists('has_permission')) {
    if (!has_permission('pos.shifts.manage')) {
        die('Access denied: You do not have permission to manage shifts.');
    }
}

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

// Get current user
$current_user = [];
if (function_exists('current_user')) {
    $current_user = current_user();
} elseif (isset($_SESSION)) {
    $current_user = $_SESSION;
}

// Get shift ID from URL
$shift_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$shift_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid shift ID');
    }
    redirect('admin/pos/shifts/index.php');
}

// Get shift data with details
$shift = null;
if (function_exists('db_fetch_one')) {
    try {
        $shift = db_fetch_one("
            SELECT 
                s.*,
                u.first_name, u.last_name,
                o.outlet_name,
                (SELECT COUNT(*) FROM pos_sales WHERE shift_id = s.shift_id) as transaction_count
            FROM pos_shifts s
            JOIN users u ON s.user_id = u.user_id
            JOIN pos_outlets o ON s.outlet_id = o.outlet_id
            WHERE s.shift_id = ?
        ", [$shift_id]);
    } catch (Exception $e) {
        error_log("Error fetching shift: " . $e->getMessage());
    }
}

if (!$shift) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Shift not found');
    }
    redirect('admin/pos/shifts/index.php');
}

// Get all sales for this shift
$sales = [];
if (function_exists('db_fetch_all')) {
    try {
        $sales = db_fetch_all("
            SELECT 
                s.*,
                pm.method_name,
                COUNT(si.item_id) as item_count
            FROM pos_sales s
            JOIN payment_methods pm ON s.payment_method_id = pm.payment_method_id
            LEFT JOIN pos_sale_items si ON s.sale_id = si.sale_id
            WHERE s.shift_id = ?
            GROUP BY s.sale_id
            ORDER BY s.sale_time
        ", [$shift_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching sales: " . $e->getMessage());
    }
}

// Get sales by payment method
$payment_breakdown = [];
if (function_exists('db_fetch_all')) {
    try {
        $payment_breakdown = db_fetch_all("
            SELECT 
                pm.method_name,
                COUNT(*) as count,
                COALESCE(SUM(s.total_amount), 0) as total,
                COALESCE(SUM(CASE WHEN s.transaction_type = 'return' THEN s.total_amount ELSE 0 END), 0) as refunds
            FROM pos_sales s
            JOIN payment_methods pm ON s.payment_method_id = pm.payment_method_id
            WHERE s.shift_id = ?
            GROUP BY pm.payment_method_id
        ", [$shift_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payment breakdown: " . $e->getMessage());
    }
}

// Get hourly breakdown
$hourly = [];
if (function_exists('db_fetch_all')) {
    try {
        $hourly = db_fetch_all("
            SELECT 
                HOUR(sale_time) as hour,
                COUNT(*) as transactions,
                COALESCE(SUM(total_amount), 0) as total
            FROM pos_sales
            WHERE shift_id = ? AND payment_status = 'completed'
            GROUP BY HOUR(sale_time)
            ORDER BY hour
        ", [$shift_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching hourly breakdown: " . $e->getMessage());
    }
}

// Get top products sold during shift
$top_products = [];
if (function_exists('db_fetch_all')) {
    try {
        $top_products = db_fetch_all("
            SELECT 
                p.product_name,
                SUM(si.quantity) as quantity,
                SUM(si.total_amount) as total
            FROM pos_sale_items si
            JOIN pos_sales s ON si.sale_id = s.sale_id
            JOIN pos_products p ON si.product_id = p.product_id
            WHERE s.shift_id = ?
            GROUP BY p.product_id
            ORDER BY quantity DESC
            LIMIT 10
        ", [$shift_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching top products: " . $e->getMessage());
    }
}

// Calculate difference
$difference = ($shift['closing_cash'] ?? 0) - ($shift['expected_cash'] ?? 0);

// Include header with error handling
$header_file = $base_path . '/views/partials/header.php';
if (file_exists($header_file)) {
    require_once $header_file;
} else {
    // Fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php echo $page_title; ?></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
        <style>
            .content-header { padding: 20px; background: #f4f6f9; }
            .card { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); margin-bottom: 20px; }
            .badge-lg { font-size: 1rem; padding: 0.5rem 1rem; }
            .info-box { min-height: 80px; margin-bottom: 10px; }
            .info-box .info-box-icon { width: 60px; height: 60px; line-height: 60px; font-size: 1.8rem; }
            .info-box .info-box-content { margin-left: 70px; }
            @media print {
                .btn-group, .breadcrumb, .card-header .card-tools { display: none; }
            }
        </style>
    </head>
    <body>
    <?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">Shift Reconciliation</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/pos/dashboard.php'); ?>">POS</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/pos/shifts/index.php'); ?>">Shifts</a></li>
                    <li class="breadcrumb-item active">Reconciliation</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Flash Messages -->
        <?php if (isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['flash_message']['type']; ?> alert-dismissible fade show">
                <?php echo $_SESSION['flash_message']['message']; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
            <?php unset($_SESSION['flash_message']); ?>
        <?php endif; ?>

        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="<?php echo base_url('admin/pos/shifts/index.php'); ?>" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Shifts
                    </a>
                    <button type="button" class="btn btn-primary" onclick="window.print()">
                        <i class="fas fa-print mr-1"></i> Print Report
                    </button>
                    <?php if ($shift['status'] == 'open'): ?>
                    <a href="<?php echo base_url('admin/pos/shifts/close.php?id=' . $shift_id); ?>" class="btn btn-warning">
                        <i class="fas fa-edit mr-1"></i> Close Shift
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Shift Summary -->
        <div class="row">
            <div class="col-md-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock mr-1"></i>
                            Shift Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info elevation-1">
                                        <i class="fas fa-hashtag"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Shift Code</span>
                                        <span class="info-box-number"><?php echo escape_html($shift['shift_code'] ?? 'N/A'); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-success elevation-1">
                                        <i class="fas fa-user"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Cashier</span>
                                        <span class="info-box-number"><?php echo escape_html($shift['first_name'] ?? ''); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning elevation-1">
                                        <i class="fas fa-store"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Outlet</span>
                                        <span class="info-box-number"><?php echo escape_html($shift['outlet_name'] ?? 'N/A'); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-danger elevation-1">
                                        <i class="fas fa-receipt"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Transactions</span>
                                        <span class="info-box-number"><?php echo $shift['transaction_count'] ?? 0; ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-md-3">
                                <strong>Opened:</strong><br>
                                <?php echo format_datetime($shift['opened_at'] ?? null); ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Closed:</strong><br>
                                <?php echo isset($shift['closed_at']) ? format_datetime($shift['closed_at']) : 'Not closed'; ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Duration:</strong><br>
                                <?php 
                                if (isset($shift['closed_at']) && isset($shift['opened_at'])) {
                                    $start = new DateTime($shift['opened_at']);
                                    $end = new DateTime($shift['closed_at']);
                                    $interval = $start->diff($end);
                                    echo $interval->format('%h hours %i minutes');
                                } elseif (isset($shift['opened_at'])) {
                                    echo 'Still open';
                                } else {
                                    echo 'N/A';
                                }
                                ?>
                            </div>
                            <div class="col-md-3">
                                <strong>Status:</strong><br>
                                <span class="badge badge-<?php echo ($shift['status'] ?? '') == 'reconciled' ? 'success' : (($shift['status'] ?? '') == 'closed' ? 'warning' : 'primary'); ?> badge-lg">
                                    <?php echo ucfirst($shift['status'] ?? 'Unknown'); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Financial Summary -->
        <div class="row">
            <div class="col-md-6">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-dollar-sign mr-1"></i>
                            Financial Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered">
                            <tr>
                                <th colspan="2" class="bg-light">Sales by Payment Method</th>
                            </tr>
                            <?php if (!empty($payment_breakdown)): ?>
                                <?php foreach ($payment_breakdown as $payment): ?>
                                <tr>
                                    <td><?php echo escape_html($payment['method_name'] ?? 'Unknown'); ?></td>
                                    <td class="text-right">
                                        <?php echo format_currency($payment['total'] ?? 0); ?>
                                        <br>
                                        <small class="text-muted"><?php echo $payment['count'] ?? 0; ?> transactions</small>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="2" class="text-center text-muted">No payment data available</td>
                                </tr>
                            <?php endif; ?>
                            
                            <tr class="table-active">
                                <th>Total Sales</th>
                                <th class="text-right"><?php echo format_currency($shift['total_sales'] ?? 0); ?></th>
                            </tr>
                            
                            <tr class="table-danger">
                                <th>Total Refunds</th>
                                <th class="text-right"><?php echo format_currency($shift['total_refunds'] ?? 0); ?></th>
                            </tr>
                            
                            <tr>
                                <th colspan="2" class="bg-light">Cash Reconciliation</th>
                            </tr>
                            <tr>
                                <td>Opening Cash</td>
                                <td class="text-right"><?php echo format_currency($shift['opening_cash'] ?? 0); ?></td>
                            </tr>
                            <tr>
                                <td>Cash Sales</td>
                                <td class="text-right">+ <?php echo format_currency($shift['cash_sales'] ?? 0); ?></td>
                            </tr>
                            <tr>
                                <td>Cash Refunds</td>
                                <td class="text-right text-danger">- <?php echo format_currency($shift['total_refunds'] ?? 0); ?></td>
                            </tr>
                            <tr class="table-info">
                                <td><strong>Expected Cash</strong></td>
                                <td class="text-right"><strong><?php echo format_currency($shift['expected_cash'] ?? 0); ?></strong></td>
                            </tr>
                            <tr>
                                <td>Actual Cash Counted</td>
                                <td class="text-right"><?php echo format_currency($shift['closing_cash'] ?? 0); ?></td>
                            </tr>
                            <tr class="<?php echo abs($difference) < 0.01 ? 'table-success' : ($difference > 0 ? 'table-warning' : 'table-danger'); ?>">
                                <td><strong>Difference</strong></td>
                                <td class="text-right">
                                    <strong><?php echo format_currency($difference); ?></strong>
                                    <br>
                                    <small>
                                        <?php 
                                        if (abs($difference) < 0.01) {
                                            echo '<span class="text-success">Perfect match</span>';
                                        } elseif ($difference > 0) {
                                            echo '<span class="text-warning">Over by ' . format_currency($difference) . '</span>';
                                        } else {
                                            echo '<span class="text-danger">Short by ' . format_currency(abs($difference)) . '</span>';
                                        }
                                        ?>
                                    </small>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Hourly Breakdown -->
            <div class="col-md-6">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Hourly Breakdown
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="hourlyChart" style="height: 300px;"></canvas>
                        
                        <div class="table-responsive mt-3">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Hour</th>
                                        <th class="text-center">Transactions</th>
                                        <th class="text-right">Sales</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($hourly)): ?>
                                        <?php foreach ($hourly as $h): ?>
                                        <tr>
                                            <td><?php echo sprintf('%02d:00 - %02d:00', $h['hour'] ?? 0, ($h['hour'] ?? 0) + 1); ?></td>
                                            <td class="text-center"><?php echo $h['transactions'] ?? 0; ?></td>
                                            <td class="text-right"><?php echo format_currency($h['total'] ?? 0); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="3" class="text-center text-muted">No hourly data available</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Products -->
        <div class="row mt-3">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-crown mr-1"></i>
                            Top Selling Products
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-right">Revenue</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($top_products)): ?>
                                        <?php foreach ($top_products as $product): ?>
                                        <tr>
                                            <td><?php echo escape_html($product['product_name'] ?? 'Unknown'); ?></td>
                                            <td class="text-center"><?php echo $product['quantity'] ?? 0; ?></td>
                                            <td class="text-right"><?php echo format_currency($product['total'] ?? 0); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="3" class="text-center text-muted">No product data available</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Shift Notes -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sticky-note mr-1"></i>
                            Shift Notes
                        </h3>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($shift['notes'])): ?>
                            <p><?php echo nl2br(escape_html($shift['notes'])); ?></p>
                        <?php else: ?>
                            <p class="text-muted">No notes recorded for this shift.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Reconciliation Actions -->
                <?php if (isset($shift['status']) && $shift['status'] == 'closed'): ?>
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-check-circle mr-1"></i>
                            Mark as Reconciled
                        </h3>
                    </div>
                    <div class="card-body">
                        <p>Once reviewed, you can mark this shift as reconciled.</p>
                        <form method="POST" action="<?php echo base_url('admin/pos/shifts/reconcile.php'); ?>">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="shift_id" value="<?php echo $shift_id; ?>">
                            <button type="submit" class="btn btn-success" onclick="return confirm('Mark this shift as reconciled?')">
                                <i class="fas fa-check-circle mr-1"></i> Mark Reconciled
                            </button>
                        </form>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    // Hourly Chart
    const ctx = document.getElementById('hourlyChart');
    
    <?php
    $hours = array_column($hourly, 'hour');
    $totals = array_column($hourly, 'total');
    ?>
    
    if (ctx && <?php echo !empty($hourly) ? 'true' : 'false'; ?>) {
        new Chart(ctx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_map(function($h) { return sprintf('%02d:00', $h); }, $hours)); ?>,
                datasets: [{
                    label: 'Sales',
                    data: <?php echo json_encode($totals); ?>,
                    backgroundColor: '#28a745',
                    borderColor: '#218838',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '<?php echo CURRENCY_SYMBOL; ?>' + value.toFixed(2);
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>

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