<?php
/**
 * Customer Dashboard - Updated Version
 * Properly fetches and displays all records from database
 */

// Initialize the application
require_once '../app/Core/init.php';

// Helper function to ensure numeric value
function ensureNumeric($value, $default = 0) {
    if (is_array($value)) {
        // If it's an array, try to extract common keys
        if (isset($value['total'])) return (float)$value['total'];
        if (isset($value['count'])) return (float)$value['count'];
        if (isset($value['balance'])) return (float)$value['balance'];
        return $default;
    }
    return is_numeric($value) ? (float)$value : $default;
}

// Authentication check
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../');
    exit();
}

// Initialize models
$userModel = new User();
$customerModel = new Customer();
$orderModel = new Order();
$walletModel = new Wallet();

// Get current user data
// $user = $userModel->findById($_SESSION['user_id']);
// if (!$user) {
//     header('Location: ../auth/logout.php');
//     exit();
// }

// Get customer data using user_id
$customer = $customerModel->findByUserId($_SESSION['user_id']);
if (!$customer) {
    die('Customer profile not found. Please contact support.');
}

// Get customer data using user_id from session
// $customer = $customerModel->findByUserId($_SESSION['user_id']);
// if (!$customer) {
//     header('Location: ../index.php');
//     exit();
// }

$customer_id = $customer['id'];

// ===== DASHBOARD DATA FETCHING =====

// 1. Order Statistics
$totalOrders = ensureNumeric($orderModel->getCustomerTotalOrders($customer_id), 0);
$activeOrders = ensureNumeric($orderModel->getCustomerActiveOrders($customer_id), 0);
$completedOrders = ensureNumeric($orderModel->getCustomerCompletedOrders($customer_id), 0);
$totalSpent = ensureNumeric($orderModel->getCustomerTotalSpent($customer_id), 0);

// 2. Wallet Data
$wallet = $walletModel->findByUserId($_SESSION['user_id']) ?? ['balance' => 0];
// Ensure wallet is an array and balance is numeric
if (!is_array($wallet)) {
    $wallet = ['balance' => 0];
}
$wallet['balance'] = ensureNumeric($wallet['balance'] ?? 0, 0);

// 3. Recent Orders (last 5 orders)
$recentOrders = $orderModel->getRecentOrdersByCustomer($customer_id, 5);
$recentOrders = is_array($recentOrders) ? $recentOrders : [];

// 4. Monthly Revenue (current month)
$currentMonthRevenue = ensureNumeric($orderModel->getCustomerMonthlySpent($customer_id, date('Y-m')), 0);

// 5. Monthly Orders for Chart (last 12 months)
$monthlyOrders = $orderModel->getCustomerMonthlyOrders($customer_id, 12);
$monthlyOrders = is_array($monthlyOrders) ? $monthlyOrders : [];

// 6. Unread Messages Count (if messages table exists)
try {
    $unreadCount = 0; // Placeholder - implement if messages system exists
} catch (Exception $e) {
    $unreadCount = 0;
}

// Page variables
$page_title = "Dashboard";
$active_menu = "dashboard";

include '../templates/layouts/customer/head.php';
?>

</head>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar  -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <a href="index.php" class="sidebar-brand">
                    <img class="sidebar-brand_icon" src="../assets/dist/img/mini-logo.png" alt="">
                    <span class="sidebar-brand_text">rentidium</span>
                </a>
            </div>
            <!--/.sidebar header-->
            <div class="sidebar-body">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div><!-- sidebar-body -->
        </nav>
        <!-- Page Content  -->
        <div class="content-wrapper">
            <div class="main-content">
                <!-- Star navbar -->
                <?php include '../templates/layouts/customer/header.php'; ?>
                <!-- End /. navbar -->
                <div class="body-content">
                    <div class="decoration blur-2"></div>
                    <div class="decoration blur-3"></div>
                    <div class="container-xxl">
                        <!-- Start header banner -->
                        <div class="header-banner align-items-center d-flex justify-content-between mb-3 p-4 rounded-4 w-100">
                            <div class="header-banner-context">
                                <h3 class="align-items-center d-flex fs-5 gap-2 text-white mb-3">
                                    <img src="../assets/dist/img/photoshop.png" alt="" width="35">
                                    Welcome to rentidium
                                </h3>
                                <div class="content-text fs-14 opacity-75 text-white">Find amazing items to rent for your needs. Your satisfaction is our priority!</div>
                                <a href="../" class="content-button btn btn-light mt-3">Start Browsing</a>
                            </div>
                            <img class="content-wrapper-img" src="../assets/dist/img/glass.png" alt="" width="180">
                        </div>
                        <!-- End /. header banner -->
                        <div class="row g-3 mb-3">
                            <div class="col-sm-6 col-md-6 col-lg-6 col-xl-3 d-flex">
                                <div class="card flex-column flex-fill p-4 position-relative shadow w-100 widget-card">
                                    <div class="d-flex">
                                        <div class="flex-grow-1 ms-3">
                                            <div class="fs-14 text-muted">Total Orders</div>
                                            <h3 class="fw-semi-bold mb-0 counter"><?= number_format(ensureNumeric($totalOrders, 0)) ?></h3>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <img src="../assets/dist/img/graph-v1.png" alt="">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6 col-md-6 col-lg-6 col-xl-3 d-flex">
                                <div class="card flex-column flex-fill p-4 position-relative shadow w-100 widget-card">
                                    <div class="d-flex">
                                        <div class="flex-grow-1 ms-3">
                                            <div class="fs-14 text-muted">Active Rentals</div>
                                            <h3 class="fw-semi-bold mb-0 counter"><?= number_format(ensureNumeric($activeOrders, 0)) ?></h3>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <img src="../assets/dist/img/degrees.png" alt="">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6 col-md-6 col-lg-6 col-xl-3 d-flex">
                                <div class="card flex-column flex-fill p-4 position-relative shadow w-100 widget-card">
                                    <div class="d-flex">
                                        <div class="flex-grow-1 ms-3">
                                            <div class="fs-14 text-muted">Wallet Balance</div>
                                            <h3 class="fw-semi-bold mb-0 counter">₦<?= number_format(ensureNumeric($wallet['balance'] ?? 0, 0), 2) ?></h3>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <img src="../assets/dist/img/sales-performance-v2.png" alt="">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6 col-md-6 col-lg-6 col-xl-3 d-flex">
                                <div class="card flex-column flex-fill p-4 position-relative shadow w-100 widget-card">
                                    <div class="d-flex">
                                        <div class="flex-grow-1 ms-3">
                                            <div class="fs-14 text-muted">Completed Orders</div>
                                            <h3 class="fw-semi-bold mb-0 counter"><?= number_format(ensureNumeric($completedOrders, 0)) ?></h3>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <img src="../assets/dist/img/graph-v1.png" alt="">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card mb-3 p-4 total-box">
                            <div class="g-4 gx-xxl-5 row">
                                <div class="col-sm-4 total-box-left">
                                    <div class="align-items-center d-flex justify-content-between mb-4">
                                        <h6 class="mb-0">Total Spent</h6>
                                        <div class="align-items-center d-flex justify-content-center rounded arrow-btn percentage-increase">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" class="bi bi-arrow-up-right" viewBox="0 0 16 16">
                                                <path fill-rule="evenodd" d="M14 2.5a.5.5 0 0 0-.5-.5h-6a.5.5 0 0 0 0 1h4.793L2.146 13.146a.5.5 0 0 0 .708.708L13 3.707V8.5a.5.5 0 0 0 1 0z" />
                                            </svg>
                                        </div>
                                    </div>
                                    <h1 class="price">₦<span class="counter"><?= number_format(ensureNumeric($totalSpent, 0), 2) ?></span></h1>
                                    <p class="mb-0 fw-semibold fs-14">
                                        <span class="percentage-increase">All Time</span>&nbsp;&nbsp; Lifetime spending
                                    </p>
                                </div>
                                <div class="col-sm-4 total-box-left">
                                    <div class="align-items-center d-flex justify-content-between mb-4">
                                        <h6 class="mb-0">This Month</h6>
                                        <div class="align-items-center d-flex justify-content-center rounded arrow-btn percentage-increase">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" class="bi bi-arrow-up-right" viewBox="0 0 16 16">
                                                <path fill-rule="evenodd" d="M14 2.5a.5.5 0 0 0-.5-.5h-6a.5.5 0 0 0 0 1h4.793L2.146 13.146a.5.5 0 0 0 .708.708L13 3.707V8.5a.5.5 0 0 0 1 0z" />
                                            </svg>
                                        </div>
                                    </div>
                                    <h1 class="price counter">₦<?= number_format(ensureNumeric($currentMonthRevenue, 0), 2) ?></h1>
                                    <p class="mb-0 fw-semibold fs-14">
                                        <span class="percentage-increase">Current</span>&nbsp;&nbsp; Month spending
                                    </p>
                                </div>
                                <div class="col-sm-4 total-box__right">
                                    <div class="align-items-center d-flex justify-content-between mb-4">
                                        <h6 class="mb-0">Messages</h6>
                                        <div class="align-items-center d-flex justify-content-center rounded text-primary arrow-btn">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" class="bi bi-arrow-down-right" viewBox="0 0 16 16">
                                                <path fill-rule="evenodd" d="M14 13.5a.5.5 0 0 1-.5.5h-6a.5.5 0 0 1 0-1h4.793L2.146 2.854a.5.5 0 1 1 .708-.708L13 12.293V7.5a.5.5 0 0 1 1 0z" />
                                            </svg>
                                        </div>
                                    </div>
                                    <h1 class="price counter"><?= $unreadCount ?></h1>
                                    <p class="mb-0 fw-semibold fs-14">
                                        <span class="text-primary">Unread</span>&nbsp;&nbsp; Messages waiting
                                    </p>
                                </div>
                            </div>
                        </div>
                        <!-- Start statistics -->
                        <div class="card mb-3">
                            <div class="card-header position-relative">
                                <h6 class="fs-17 fw-semi-bold my-1">Rental Activity</h6>
                            </div>
                            <div class="card-body">
                                <div id="chart"></div>
                            </div>
                        </div>
                        <!-- End /. statistics -->
                        <div class="card">
                            <div class="card-header position-relative">
                                <h6 class="fs-17 fw-semi-bold my-1">Recent Orders</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-borderless text-nowrap category-list">
                                        <thead>
                                            <tr>
                                                <th>SL</th>
                                                <th>Item</th>
                                                <th>Vendor</th>
                                                <th>Order Date</th>
                                                <th>Duration</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th class="text-end">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($recentOrders)): ?>
                                                <tr>
                                                    <td colspan="8" class="text-center py-4">
                                                        <div class="text-muted">
                                                            <i class="fas fa-shopping-bag fa-2x mb-2"></i>
                                                            <p>No orders yet. Start browsing items to make your first rental!</p>
                                                            <a href="../" class="btn btn-primary btn-sm">Browse Items</a>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php else: ?>
                                                <?php $count = 1; ?>
                                                <?php foreach ($recentOrders as $order): ?>
                                                    <tr>
                                                        <th><?= str_pad($count++, 2, '0', STR_PAD_LEFT) ?></th>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <span class="avatar avatar-sm avatar-circle me-2">
                                                                    <img class="avatar-img" src="<?= !empty($order['main_image']) ? upload('items/' . $order['main_image']) : '../assets/dist/img/placeholder.jpg' ?>" alt="Item">
                                                                </span>
                                                                <div>
                                                                    <h6 class="mb-0"><?= esc($order['title'] ?? 'Item') ?></h6>
                                                                    <small class="text-muted"><?= esc($order['category_name'] ?? 'Category') ?></small>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td><?= esc($order['vendor_name'] ?? 'Vendor') ?></td>
                                                        <td><?= date('M d, Y', strtotime($order['created_at'])) ?></td>
                                                        <td>
                                                            <?php
                                                            $startDate = new DateTime($order['start_date']);
                                                            $endDate = new DateTime($order['end_date']);
                                                            $duration = $startDate->diff($endDate)->days;
                                                            echo $duration . ' day' . ($duration != 1 ? 's' : '');
                                                            ?>
                                                        </td>
                                                        <td>₦<?= number_format(ensureNumeric($order['total_amount'] ?? 0, 0), 2) ?></td>
                                                        <td>
                                                            <div class="align-items-center d-flex fw-medium gap-1 fs-14">
                                                                <?php
                                                                switch ($order['status']) {
                                                                    case 'pending':
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-warning"></i><span class="text-warning">Pending</span>';
                                                                        break;
                                                                    case 'confirmed':
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-primary"></i><span class="text-primary">Confirmed</span>';
                                                                        break;
                                                                    case 'ongoing':
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-success"></i><span class="text-success">Ongoing</span>';
                                                                        break;
                                                                    case 'completed':
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-success"></i><span class="text-success">Completed</span>';
                                                                        break;
                                                                    case 'cancelled':
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-danger"></i><span class="text-danger">Cancelled</span>';
                                                                        break;
                                                                    default:
                                                                        echo '<i class="fa-circle fa-solid fs-10 text-secondary"></i><span class="text-secondary">' . ucfirst($order['status']) . '</span>';
                                                                }
                                                                ?>
                                                            </div>
                                                        </td>
                                                        <td class="text-end">
                                                            <a href="orders.php?id=<?= $order['id'] ?>" class="btn btn-primary fw-medium btn-sm d-inline-flex align-items-center justify-content-center gap-1">
                                                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye" viewBox="0 0 16 16">
                                                                    <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8M1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z" />
                                                                    <path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0" />
                                                                </svg>
                                                                View
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!--/.body content-->
            </div>
            <!--/.main content-->
            <?php include '../templates/layouts/customer/footer.php'; ?>
    <script>
        /*-------------------------------------------
            Toastr Welcome Message
        --------------------------------------------- */
        setTimeout(function () {
            toastr.options = {
                closeButton: true,
                progressBar: true,
                showMethod: 'slideDown',
                timeOut: 5000
            };
            toastr.success('Welcome back, <?= addslashes($customer['first_name'] ?? 'Customer') ?>!', 'Customer Dashboard');
        }, 500);

        // Rental Activity Chart
        const monthlyData = <?= json_encode($monthlyOrders) ?>;
        const chartOptions = {
            chart: {
                type: 'area',
                height: 350,
                toolbar: {
                    show: false
                }
            },
            series: [{
                name: 'Orders',
                data: monthlyData.map(item => item.count || 0)
            }],
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: 2
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.7,
                    opacityTo: 0.9,
                }
            },
            xaxis: {
                categories: monthlyData.map(item => item.month || 'Month')
            },
            colors: ['#5D5FEF']
        };

        if (monthlyData.length > 0) {
            const chart = new ApexCharts(document.querySelector("#chart"), chartOptions);
            chart.render();
        }
    </script>
</body>

</html>