<?php
/**
 * VENDOR CALENDAR PAGE
 * File: vendor/calendar.php
 * View all bookings and manage availability in calendar view
 */

require_once '../app/Core/init.php';

// Require vendor authentication
Auth::requireVendor();

$page_title = "Booking Calendar";
$active_menu = "calendar";

// Initialize models
$db = Database::getInstance();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('profile.php');
}

// Get parameters for filtering
$item_id = isset($_GET['item_id']) ? (int)$_GET['item_id'] : 0;
$view = $_GET['view'] ?? 'month'; // month, week, day
$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');

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

// Get vendor's items for filter dropdown
$items_sql = "SELECT id, title FROM items WHERE vendor_id = ? AND approval_status = 'approved' ORDER BY title";
$vendor_items = $db->fetchAll($items_sql, [$vendor_data['id']]);

// Build WHERE clause for bookings
$where_conditions = ["i.vendor_id = ?"];
$params = [$vendor_data['id']];

if ($item_id > 0) {
    $where_conditions[] = "o.item_id = ?";
    $params[] = $item_id;
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get bookings for the selected period
$bookings_sql = "SELECT 
    o.*,
    i.title as item_title,
    i.main_image as item_image,
    CONCAT(c.first_name, ' ', c.last_name) as customer_name,
    c.phone as customer_phone,
    DATEDIFF(o.end_date, o.start_date) + 1 as duration_days
FROM orders o
JOIN items i ON o.item_id = i.id
LEFT JOIN customers c ON o.customer_id = c.id
$where_clause
AND o.status IN ('confirmed', 'ongoing')
AND (
    (o.start_date BETWEEN ? AND ?) OR 
    (o.end_date BETWEEN ? AND ?) OR 
    (o.start_date <= ? AND o.end_date >= ?)
)
ORDER BY o.start_date ASC";

// Calculate date range based on view
$start_date = date('Y-m-01', strtotime("$year-$month-01"));
$end_date = date('Y-m-t', strtotime($start_date));

$booking_params = array_merge($params, [
    $start_date, $end_date,
    $start_date, $end_date,
    $start_date, $start_date
]);

$bookings = $db->fetchAll($bookings_sql, $booking_params);

// Get availability data for the vendor's items
$availability_sql = "SELECT 
    ac.*,
    i.title as item_title,
    o.order_number
FROM availability_calendar ac
JOIN items i ON ac.item_id = i.id
LEFT JOIN orders o ON ac.order_id = o.id
WHERE i.vendor_id = ? AND ac.date BETWEEN ? AND ?
ORDER BY ac.date ASC, i.title ASC";

$availability = $db->fetchAll($availability_sql, [$vendor_data['id'], $start_date, $end_date]);

// Group bookings by date for easy display
$bookings_by_date = [];
foreach ($bookings as $booking) {
    $current_date = $booking['start_date'];
    $end_date_obj = new DateTime($booking['end_date']);
    
    while ($current_date <= $booking['end_date']) {
        if (!isset($bookings_by_date[$current_date])) {
            $bookings_by_date[$current_date] = [];
        }
        $bookings_by_date[$current_date][] = $booking;
        $current_date = date('Y-m-d', strtotime($current_date . ' +1 day'));
    }
}

// Get calendar navigation
$prev_month = $month - 1;
$prev_year = $year;
if ($prev_month < 1) {
    $prev_month = 12;
    $prev_year = $year - 1;
}

$next_month = $month + 1;
$next_year = $year;
if ($next_month > 12) {
    $next_month = 1;
    $next_year = $year + 1;
}

// Get today's date for highlighting
$today = date('Y-m-d');

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-calendar-alt"></i> Booking Calendar</h1>
            <p class="text-muted">Manage your item availability and view upcoming rentals</p>
        </div>
        <div class="header-right">
            <div class="btn-group">
                <a href="calendar.php?view=month&month=<?= date('n') ?>&year=<?= date('Y') ?>&item_id=<?= $item_id ?>" 
                   class="btn btn-outline-primary">
                    <i class="fas fa-calendar-day"></i> Today
                </a>
            </div>
        </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flash_message): ?>
        <div class="alert alert-<?= $flash_message['type'] ?>">
            <?= Security::escapeOutput($flash_message['message']) ?>
        </div>
    <?php endif; ?>

    <!-- Calendar Controls -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-3">
                    <form method="GET" class="d-flex gap-2">
                        <select name="item_id" class="form-control" onchange="this.form.submit()">
                            <option value="0">All Items</option>
                            <?php foreach ($vendor_items as $item): ?>
                                <option value="<?= $item['id'] ?>" <?= $item_id == $item['id'] ? 'selected' : '' ?>>
                                    <?= Security::escapeOutput($item['title']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="hidden" name="view" value="<?= $view ?>">
                        <input type="hidden" name="month" value="<?= $month ?>">
                        <input type="hidden" name="year" value="<?= $year ?>">
                    </form>
                </div>
                
                <div class="col-md-6 text-center">
                    <div class="d-flex justify-content-center align-items-center gap-3">
                        <a href="calendar.php?view=<?= $view ?>&month=<?= $prev_month ?>&year=<?= $prev_year ?>&item_id=<?= $item_id ?>" 
                           class="btn btn-outline-secondary">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        
                        <h4 class="mb-0">
                            <?= date('F Y', strtotime("$year-$month-01")) ?>
                        </h4>
                        
                        <a href="calendar.php?view=<?= $view ?>&month=<?= $next_month ?>&year=<?= $next_year ?>&item_id=<?= $item_id ?>" 
                           class="btn btn-outline-secondary">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </div>
                </div>
                
                <div class="col-md-3 text-end">
                    <div class="btn-group">
                        <a href="calendar.php?view=month&month=<?= $month ?>&year=<?= $year ?>&item_id=<?= $item_id ?>" 
                           class="btn btn-<?= $view === 'month' ? 'primary' : 'outline-primary' ?>">
                            Month
                        </a>
                        <a href="calendar.php?view=week&month=<?= $month ?>&year=<?= $year ?>&item_id=<?= $item_id ?>" 
                           class="btn btn-<?= $view === 'week' ? 'primary' : 'outline-primary' ?>">
                            Week
                        </a>
                        <a href="calendar.php?view=day&month=<?= $month ?>&year=<?= $year ?>&item_id=<?= $item_id ?>" 
                           class="btn btn-<?= $view === 'day' ? 'primary' : 'outline-primary' ?>">
                            Day
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Calendar View -->
    <div class="card">
        <div class="card-body p-0">
            <?php if ($view === 'month'): ?>
                <!-- Month View -->
                <div class="calendar-month">
                    <!-- Weekday Headers -->
                    <div class="calendar-header">
                        <?php
                        $weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
                        foreach ($weekdays as $weekday):
                        ?>
                            <div class="calendar-weekday">
                                <strong><?= $weekday ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Calendar Grid -->
                    <div class="calendar-grid">
                        <?php
                        // Get first day of month and total days
                        $first_day = date('N', strtotime("$year-$month-01")); // 1=Monday, 7=Sunday
                        $total_days = date('t', strtotime("$year-$month-01"));
                        
                        // Adjust for Sunday start (if first day is Monday (1), we need 0 blank days)
                        $start_blank = $first_day == 7 ? 0 : $first_day;
                        
                        // Add blank days for the first week
                        for ($i = 0; $i < $start_blank; $i++):
                        ?>
                            <div class="calendar-day empty"></div>
                        <?php endfor;
                        
                        // Add days of the month
                        for ($day = 1; $day <= $total_days; $day++):
                            $current_date = date('Y-m-d', strtotime("$year-$month-$day"));
                            $is_today = $current_date === $today;
                            $day_bookings = $bookings_by_date[$current_date] ?? [];
                        ?>
                            <div class="calendar-day <?= $is_today ? 'today' : '' ?>">
                                <div class="day-header">
                                    <span class="day-number"><?= $day ?></span>
                                    <?php if ($is_today): ?>
                                        <span class="badge bg-primary today-badge">Today</span>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="day-bookings">
                                    <?php foreach ($day_bookings as $booking): ?>
                                        <div class="booking-item" 
                                             data-bs-toggle="tooltip" 
                                             title="<?= Security::escapeOutput($booking['item_title']) ?> - <?= Security::escapeOutput($booking['customer_name']) ?>">
                                            <div class="booking-dot bg-<?= $booking['status'] === 'ongoing' ? 'success' : 'info' ?>"></div>
                                            <small class="booking-text">
                                                <?= Security::escapeOutput($booking['item_title']) ?>
                                            </small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                
                                <?php if (count($day_bookings) > 2): ?>
                                    <div class="more-bookings">
                                        <small class="text-muted">+<?= count($day_bookings) - 2 ?> more</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endfor; ?>
                    </div>
                </div>
                
            <?php elseif ($view === 'week'): ?>
                <!-- Week View -->
                <div class="calendar-week">
                    <div class="calendar-week-header">
                        <?php
                        $week_start = date('Y-m-d', strtotime("$year-$month-01"));
                        for ($i = 0; $i < 7; $i++):
                            $week_date = date('Y-m-d', strtotime($week_start . " +$i days"));
                            $is_today = $week_date === $today;
                        ?>
                            <div class="week-day-header <?= $is_today ? 'today' : '' ?>">
                                <div class="week-day-name"><?= date('D', strtotime($week_date)) ?></div>
                                <div class="week-day-date"><?= date('j', strtotime($week_date)) ?></div>
                            </div>
                        <?php endfor; ?>
                    </div>
                    
                    <div class="week-bookings-container">
                        <?php for ($i = 0; $i < 7; $i++):
                            $week_date = date('Y-m-d', strtotime($week_start . " +$i days"));
                            $day_bookings = $bookings_by_date[$week_date] ?? [];
                        ?>
                            <div class="week-day-column">
                                <?php foreach ($day_bookings as $booking): ?>
                                    <div class="week-booking-item">
                                        <div class="booking-time">
                                            <small><?= format_date($booking['start_date'], 'M j') ?> - <?= format_date($booking['end_date'], 'M j') ?></small>
                                        </div>
                                        <div class="booking-details">
                                            <strong><?= Security::escapeOutput($booking['item_title']) ?></strong>
                                            <small class="text-muted d-block"><?= Security::escapeOutput($booking['customer_name']) ?></small>
                                            <span class="badge bg-<?= $booking['status'] === 'ongoing' ? 'success' : 'info' ?>">
                                                <?= ucfirst($booking['status']) ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                
                                <?php if (empty($day_bookings)): ?>
                                    <div class="text-center text-muted py-3">
                                        <small>No bookings</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endfor; ?>
                    </div>
                </div>
                
            <?php else: ?>
                <!-- Day View -->
                <div class="calendar-day-view">
                    <?php
                    $day_date = date('Y-m-d', strtotime("$year-$month-01"));
                    $day_bookings = $bookings_by_date[$day_date] ?? [];
                    ?>
                    
                    <div class="day-view-header text-center py-3">
                        <h3><?= date('l, F j, Y', strtotime($day_date)) ?></h3>
                    </div>
                    
                    <div class="day-bookings-list">
                        <?php if (empty($day_bookings)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                <h4>No Bookings</h4>
                                <p class="text-muted">No rentals scheduled for this day.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($day_bookings as $booking): ?>
                                <div class="day-booking-item">
                                    <div class="row align-items-center">
                                        <div class="col-md-3">
                                            <?php if (!empty($booking['item_image'])): ?>
                                                <img src="<?= upload('items/' . $booking['item_image']) ?>" 
                                                     alt="<?= Security::escapeOutput($booking['item_title']) ?>"
                                                     class="rounded"
                                                     style="width: 60px; height: 60px; object-fit: cover;">
                                            <?php else: ?>
                                                <div class="bg-light rounded d-flex align-items-center justify-content-center"
                                                     style="width: 60px; height: 60px;">
                                                    <i class="fas fa-box text-muted"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <h6 class="mb-1"><?= Security::escapeOutput($booking['item_title']) ?></h6>
                                            <p class="mb-1">
                                                <strong>Customer:</strong> <?= Security::escapeOutput($booking['customer_name']) ?>
                                            </p>
                                            <p class="mb-1">
                                                <strong>Period:</strong> 
                                                <?= format_date($booking['start_date'], 'M d') ?> - 
                                                <?= format_date($booking['end_date'], 'M d') ?>
                                                (<?= $booking['duration_days'] ?> days)
                                            </p>
                                            <p class="mb-0">
                                                <strong>Amount:</strong> <?= format_money($booking['total_amount']) ?>
                                            </p>
                                        </div>
                                        
                                        <div class="col-md-3 text-end">
                                            <span class="badge bg-<?= $booking['status'] === 'ongoing' ? 'success' : 'info' ?> mb-2">
                                                <?= ucfirst($booking['status']) ?>
                                            </span>
                                            <br>
                                            <a href="order-details.php?id=<?= $booking['id'] ?>" 
                                               class="btn btn-sm btn-outline-primary">
                                                View Details
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Legend -->
    <div class="row mt-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-info-circle"></i> Legend</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6">
                            <div class="d-flex align-items-center mb-2">
                                <div class="legend-dot bg-info me-2"></div>
                                <small>Confirmed Bookings</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="d-flex align-items-center mb-2">
                                <div class="legend-dot bg-success me-2"></div>
                                <small>Ongoing Rentals</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="d-flex align-items-center mb-2">
                                <div class="legend-dot bg-primary me-2"></div>
                                <small>Today</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="d-flex align-items-center mb-2">
                                <div class="legend-dot bg-light me-2 border"></div>
                                <small>Available</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-chart-bar"></i> Quick Stats</h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-4">
                            <h5 class="text-primary mb-1"><?= count($bookings) ?></h5>
                            <small class="text-muted">Total Bookings</small>
                        </div>
                        <div class="col-4">
                            <h5 class="text-success mb-1">
                                <?= count(array_filter($bookings, function($b) { return $b['status'] === 'ongoing'; })) ?>
                            </h5>
                            <small class="text-muted">Active Now</small>
                        </div>
                        <div class="col-4">
                            <h5 class="text-info mb-1">
                                <?= count(array_filter($bookings, function($b) { return $b['status'] === 'confirmed'; })) ?>
                            </h5>
                            <small class="text-muted">Upcoming</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<style>
/* Calendar Month View */
.calendar-month {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    overflow: hidden;
}

.calendar-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    background: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

.calendar-weekday {
    padding: 12px;
    text-align: center;
    font-weight: 600;
    color: #495057;
    border-right: 1px solid #dee2e6;
}

.calendar-weekday:last-child {
    border-right: none;
}

.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
}

.calendar-day {
    min-height: 120px;
    border-right: 1px solid #dee2e6;
    border-bottom: 1px solid #dee2e6;
    padding: 8px;
    background: white;
    position: relative;
}

.calendar-day:nth-child(7n) {
    border-right: none;
}

.calendar-day.empty {
    background: #f8f9fa;
}

.calendar-day.today {
    background: #e7f3ff;
}

.day-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.day-number {
    font-weight: 600;
    color: #495057;
}

.today-badge {
    font-size: 0.7em;
    padding: 2px 6px;
}

.day-bookings {
    max-height: 80px;
    overflow-y: auto;
}

.booking-item {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
    padding: 2px 4px;
    border-radius: 4px;
    background: #f8f9fa;
    font-size: 0.8em;
}

.booking-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
    flex-shrink: 0;
}

.booking-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
}

.more-bookings {
    text-align: center;
    margin-top: 4px;
}

/* Calendar Week View */
.calendar-week-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    background: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

.week-day-header {
    padding: 12px;
    text-align: center;
    border-right: 1px solid #dee2e6;
}

.week-day-header.today {
    background: #e7f3ff;
}

.week-day-header:last-child {
    border-right: none;
}

.week-day-name {
    font-weight: 600;
    color: #495057;
}

.week-day-date {
    font-size: 1.2em;
    font-weight: 700;
    color: #212529;
}

.week-bookings-container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    min-height: 400px;
}

.week-day-column {
    border-right: 1px solid #dee2e6;
    padding: 8px;
    background: white;
}

.week-day-column:last-child {
    border-right: none;
}

.week-booking-item {
    background: #e7f3ff;
    border: 1px solid #b3d7ff;
    border-radius: 6px;
    padding: 8px;
    margin-bottom: 8px;
    font-size: 0.85em;
}

.booking-time {
    color: #666;
    margin-bottom: 4px;
}

.booking-details {
    color: #333;
}

/* Day View */
.day-booking-item {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    background: white;
}

.day-booking-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Legend */
.legend-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
}

/* Responsive */
@media (max-width: 768px) {
    .calendar-header,
    .calendar-grid {
        grid-template-columns: repeat(7, 1fr);
    }
    
    .calendar-day {
        min-height: 80px;
        font-size: 0.8em;
    }
    
    .week-bookings-container {
        grid-template-columns: 1fr;
    }
    
    .week-day-column {
        border-right: none;
        border-bottom: 1px solid #dee2e6;
    }
}
</style>

<?php //include '../templates/layouts/vendor/footer.php'; ?>