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

if (!User::isLoggedIn()){
    header("Location: login.php");
    exit();
}

$me = User::getCurrentUser(); 

try {
    $db = getDBConnection();
    
    $orders_stmt = $db->prepare("
        SELECT o.*, 
               GROUP_CONCAT(CONCAT(s.name, ' (', oi.quantity, ')') SEPARATOR ', ') as services,
               r.id as review_id
        FROM orders o
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        LEFT JOIN reviews r ON o.id = r.order_id AND r.user_id = o.user_id
        WHERE o.user_id = ?
        GROUP BY o.id
        ORDER BY o.created_at DESC
        LIMIT 10
    ");
    $orders_stmt->execute([$me['id']]);
    $orders = $orders_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $subscriptions_stmt = $db->prepare("
        SELECT * FROM subscriptions 
        WHERE user_id = ? AND status = 'active'
        ORDER BY created_at DESC
    ");
    $subscriptions_stmt->execute([$me['id']]);
    $subscriptions = $subscriptions_stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $orders = [];
    $subscriptions = [];
    error_log("Profile page error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - Allura Dry Clean</title>
    <?php include '../includes/header.php'; ?>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/notifications.css">
</head>
<body>
    <div class="profile-container">
        <?php if (isset($_SESSION['review_success'])): ?>
            <div style="background: #d4edda; color: #155724; padding: 1rem; border-radius: 5px; margin-bottom: 1rem; border: 1px solid #c3e6cb;">
                ✓ Thank you! Your review has been submitted successfully.
            </div>
            <?php unset($_SESSION['review_success']); ?>
        <?php endif; ?>
        <div class="profile-section">
            <h2 class="section-title">Personal Information</h2>
            
            <div class="account-info">
                <label>Name:</label>
                <span><?php echo htmlspecialchars($me['name']); ?></span>
            </div>
            
            <div class="account-info">
                <label>Email:</label>
                <span><?php echo htmlspecialchars($me['email']); ?></span>
            </div>
            
            <div class="account-info">
                <label>Phone:</label>
                <span><?php echo htmlspecialchars($me['phone']); ?></span>
            </div>
            
            <div class="account-info">
                <label>Address:</label>
                <span><?php echo htmlspecialchars($me['address']); ?></span>
            </div>
        </div>

        <?php if (!empty($subscriptions)): ?>
        <div class="profile-section">
            <h2 class="section-title">Active Subscriptions</h2>
            
            <?php foreach ($subscriptions as $subscription): ?>
                <?php
                $days_left = max(0, (strtotime($subscription['end_date']) - time()) / (60 * 60 * 24));
                $usage_remaining = max(0, $subscription['max_usage'] - $subscription['usage_count']);
                ?>
                <div class="subscription-card">
                    <div class="subscription-header">
                        <span class="subscription-name"><?php echo htmlspecialchars($subscription['plan_name']); ?></span>
                        <span class="subscription-type"><?php echo htmlspecialchars($subscription['plan_type']); ?></span>
                    </div>
                    
                    <div class="subscription-details">
                        <div class="subscription-detail">
                            <span class="detail-value"><?php echo ceil($days_left); ?></span>
                            <span class="detail-label">Days Remaining</span>
                        </div>
                        
                        <div class="subscription-detail">
                            <span class="detail-value"><?php echo $usage_remaining; ?></span>
                            <span class="detail-label">Orders Remaining</span>
                        </div>
                        
                        <div class="subscription-detail">
                            <span class="detail-value"><?php echo $subscription['usage_count']; ?>/<?php echo $subscription['max_usage']; ?></span>
                            <span class="detail-label">Orders Used</span>
                        </div>
                        
                        <div class="subscription-detail">
                            <span class="detail-value">SAR <?php echo number_format($subscription['price'], 2); ?></span>
                            <span class="detail-label">Plan Price</span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="profile-section">
            <h2 class="section-title">Recent Orders</h2>
            
            <?php if (!empty($orders)): ?>
                <?php foreach ($orders as $order): ?>
                    <div class="order-card">
                        <div class="order-header">
                            <span class="order-id">Order #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></span>
                            <span class="order-status status-<?php echo $order['status']; ?>">
                                <?php echo ucfirst($order['status']); ?>
                            </span>
                        </div>
                        
                        <div class="order-details">
                            <div class="order-services">
                                <strong>Services:</strong> <?php echo htmlspecialchars($order['services']); ?>
                            </div>
                            
                            <div class="order-amount">
                                Total: SAR <?php echo number_format($order['total_amount'], 2); ?>
                            </div>
                            
                            <div class="order-date">
                                Ordered on: <?php echo date('F j, Y', strtotime($order['created_at'])); ?>
                                <?php if ($order['delivery_date']): ?>
                                    | Delivery: <?php echo date('F j, Y', strtotime($order['delivery_date'])); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <?php if ($order['status'] !== 'delivered' && $order['status'] !== 'cancelled' && $order['status'] !== 'pending'): ?>
                            <div class="location-section">
                                <?php 
                                $location_data = $order['customer_location'] ? json_decode($order['customer_location'], true) : null;
                                ?>
                                <?php if ($location_data): ?>
                                    <div class="location-status">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <span class="location-confirmed">Your location has been successfully set</span>
                                        <small>Last updated: <?php echo date('d/m/Y H:i', strtotime($location_data['updated_at'])); ?></small>
                                    </div>
                                    <button onclick="updateLocation(<?php echo $order['id']; ?>)" class="btn-location-update">
                                        <i class="fas fa-sync-alt"></i> Update Location
                                    </button>
                                <?php else: ?>
                                    <div class="location-request">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <span>Please specify your current location for the delivery person</span>
                                        <button onclick="shareLocation(<?php echo $order['id']; ?>)" class="btn-location">
                                            <i class="fas fa-map-marker-alt"></i> Set Location
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($order['status'] === 'delivered'): ?>
                            <div class="review-section">
                                <?php if ($order['review_id']): ?>
                                    <span class="review-submitted">
                                        ✓ Review Submitted
                                    </span>
                                <?php else: ?>
                                    <a href="/allura/php/add_review.php?order_id=<?php echo $order['id']; ?>" class="btn-review">
                                        Rate Service & Delivery
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="no-data">
                    You haven't placed any orders yet. <a href="/allura/service.php">Browse our services</a> to get started!
                </div>
            <?php endif; ?>
        </div>

        <div class="account-actions">
            <a href="/allura/home.php" class="btn">Back to Home</a>
            <a href="/allura/service.php" class="btn">Browse Services</a>
        </div>
    </div>
    <?php include '../includes/footer.php'; ?>
    
    <script src="../js/location-picker.js"></script>
</body>
</html>