<?php
require_once 'includes/User.php';
require_once 'includes/db_config.php';

$usr = User::getCurrentUser();
$logged_in = User::isLoggedIn();

$services = [];
$error_msg = '';
$customer_type = 'guest';
$offers = [];

if ($logged_in) {
    try {
        $db = getDBConnection();
        
        $stmt = $db->prepare("
            SELECT u.*, 
                   COUNT(o.id) as order_count,
                   CASE 
                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                       WHEN COUNT(o.id) > 0 THEN 'normal'
                       ELSE 'new'
                   END as customer_type
            FROM users u 
            LEFT JOIN orders o ON u.id = o.user_id 
            WHERE u.id = ?
            GROUP BY u.id
        ");
        $stmt->execute(array($usr['id']));
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $customer_type = isset($user_data['customer_type']) ? $user_data['customer_type'] : 'new';
        
        $stmt = $db->prepare("
            SELECT * FROM offers 
            WHERE status = 'active' 
            AND start_date <= CURDATE() 
            AND end_date >= CURDATE()
            AND (target_customers = 'all' OR target_customers = ?)
            AND (usage_limit IS NULL OR used_count < usage_limit)
            ORDER BY discount_value DESC
            LIMIT 3
        ");
        $stmt->execute(array($customer_type));
        $available_offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        error_log("Error getting customer data: " . $e->getMessage());
    }
}

try {
    $db = getDBConnection();
    $st = $db->prepare("SELECT id, name, description, price, category, image FROM services ORDER BY created_at DESC");
    $st->execute();
    $svcs = $st->fetchAll(PDO::FETCH_ASSOC);
    
    $service_options = [];
    if (!empty($svcs)) {
        $options_st = $db->prepare("SELECT * FROM service_options ORDER BY service_id, option_type, price_modifier");
        $options_st->execute();
        $all_options = $options_st->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($all_options as $option) {
            $service_options[$option['service_id']][$option['option_type']][] = $option;
        }
    }
    
    if (empty($svcs)) { $err = 'No services available at the moment.'; }
} catch (PDOException $e) {
    $err = 'Error fetching services: ' . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Our Services - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
</head>
<body>
    <div class="services-container">
        <div class="page-header">
            <h1>Choose the Service That Suits You – Smart Washing & Delivery to Your Doorstep</h1>
            <p>Professional cleaning services with customizable options and convenient delivery</p>
        </div>
        
        <?php if (!empty($err)): ?>
            <div class="error-message">
                <p><?php echo htmlspecialchars($err); ?></p>
            </div>
        <?php endif; ?>
        
        <?php if (empty($svcs) && empty($err)): ?>
            <div class="no-services">
                <p>No services available at the moment. Please check back later.</p>
            </div>
        <?php else: ?>
            <div class="services-grid">
                <?php foreach ($svcs as $service): ?>
                <?php 
                    $total_options = 0;
                    if (isset($service_options[$service['id']])) {
                        foreach ($service_options[$service['id']] as $option_type => $options) {
                            $total_options += count($options);
                        }
                    }
                    
                    $card_class = 'enhanced-service-card';
                    if ($total_options >= 15) {
                        $card_class .= ' has-very-many-options';
                    } elseif ($total_options >= 8) {
                        $card_class .= ' has-many-options';
                    }
                ?>
                <div class="<?php echo $card_class; ?>" data-service-id="<?php echo $service['id']; ?>">
                    <div class="service-image">
                        <img src="<?php echo htmlspecialchars($service['image']); ?>" alt="<?php echo htmlspecialchars($service['name']); ?>" onerror="this.src='/allura/img/default-service.png'">
                        <?php if ($logged_in && !empty($available_offers)): ?>
                        <div class="offer-badge">
                            <?php 
                                $applicable_offers = array_filter($available_offers, function($offer) use ($service) {
                                    return empty($offer['applicable_services']) || in_array($service['id'], json_decode($offer['applicable_services'], true));
                                });
                                if (!empty($applicable_offers)):
                                    $offer = reset($applicable_offers);
                            ?>
                                <?php if ($offer['discount_type'] === 'percentage'): ?>
                                    <?php echo $offer['discount_value']; ?>% OFF
                                <?php else: ?>
                                    SAR <?php echo number_format($offer['discount_value'], 2); ?> OFF
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="service-content">
                        <h3><?php echo htmlspecialchars($service['name']); ?></h3>
                        <p class="service-description"><?php echo htmlspecialchars($service['description']); ?></p>
                        
                       
                        
                        <div class="service-actions">
                            <a href="/allura/service_details.php?id=<?php echo $service['id']; ?>" class="btn btn-primary view-details-btn">
                                View Details & Order
                            </a>
                            <?php if (!$logged_in): ?>
                            <p class="login-note">
                                <small>Please <a href="/allura/login.php">login</a> to place an order</small>
                            </p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php include 'includes/footer.php'; ?>
    
    <?php if ($logged_in): ?>
    <script src="/allura/js/discounts.js"></script>
    <script src="/allura/js/script.js"></script>
    <?php endif; ?>
</body>
</html>