<?php
/**
 * User Orders / Purchases Page (Pro Design - Status Sync Fixed)
 */
require_once 'includes/db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) { 
    header("Location: login"); 
    exit; 
}
$user_id = $_SESSION['user_id'];

// --- SELF HEALING DATABASE ---
try {
    $pdo->exec("ALTER TABLE products ADD COLUMN IF NOT EXISTS setup_video_url VARCHAR(255) NULL");
} catch (PDOException $e) {}

// Auto-Approve check based on recent payment success
// Sometimes the session check clears too fast or redirect happens before DB sync.
// If there's an invoice in URL from a redirect, ensure it's approved if it was a success callback.
if (isset($_GET['invoice_no']) && isset($_GET['status']) && $_GET['status'] == 'success') {
    $inv = $_GET['invoice_no'];
    $stmt = $pdo->prepare("UPDATE orders SET status = 'approved' WHERE invoice_no = ? AND user_id = ? AND status != 'approved'");
    $stmt->execute([$inv, $user_id]);
}

// Fetch User Data
try {
    $u = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $u->execute([$user_id]);
    $user = $u->fetch();

    // Fetch Orders
    $orders = $pdo->prepare("SELECT o.*, p.title, p.main_image, p.download_file, p.setup_video_url FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.user_id = ? ORDER BY o.id DESC");
    $orders->execute([$user_id]);
    $all_orders = $orders->fetchAll();
} catch (PDOException $e) {
    $all_orders = [];
}

$page_title = 'My Purchases';
require_once 'includes/header.php';
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    body { 
        background-color: #f8fafc; 
        color: #334155; 
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
        margin: 0;
        padding: 0;
    }

    /* Hide the default website header to make it a full page app-like view */
    header, .main-header { 
        display: none !important; 
    }
    
    .account-wrapper { 
        margin: 0 auto 100px;
        max-width: 1000px; 
    }

    /* Full Width Top App Bar */
    .app-header {
        display: flex;
        align-items: center;
        gap: 15px;
        background: #00059E; /* Deep Blue */
        color: #ffffff;
        padding: 16px 20px;
        position: sticky;
        top: 0;
        z-index: 999;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .btn-back {
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        text-decoration: none;
    }

    .section-title { 
        font-size: 1.25rem; 
        font-weight: 700; 
        color: #ffffff; 
        margin: 0; 
    }

    /* Order Cards Grid */
    .orders-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 20px;
        padding: 20px;
    }

    .order-card {
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #e2e8f0;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .order-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.05);
    }

    .order-img-wrapper {
        position: relative;
        width: 100%;
        padding-top: 56.25%; /* 16:9 Aspect Ratio */
        background: #f1f5f9;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .order-img-wrapper img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .order-status-badge {
        position: absolute;
        top: 10px;
        right: 10px;
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 0.75rem;
        font-weight: 800;
        text-transform: uppercase;
        backdrop-filter: blur(4px);
    }
    .status-pending { background: rgba(245, 158, 11, 0.9); color: #fff; }
    .status-completed, .status-approved { background: rgba(16, 185, 129, 0.9); color: #fff; }
    .status-failed, .status-rejected { background: rgba(239, 68, 68, 0.9); color: #fff; }

    .order-content {
        padding: 15px;
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    .order-title {
        font-size: 1.1rem;
        font-weight: 700;
        color: #0f172a;
        margin: 0 0 5px 0;
        line-height: 1.3;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .order-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        font-size: 0.85rem;
        color: #64748b;
    }
    
    .order-price {
        font-size: 1.1rem;
        font-weight: 800;
        color: #00059E;
    }

    .order-actions {
        margin-top: auto;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .btn-action {
        flex: 1;
        text-align: center;
        padding: 10px;
        border-radius: 6px;
        font-weight: 600;
        font-size: 0.9rem;
        text-decoration: none;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        transition: 0.2s;
    }
    
    .btn-download {
        background: #10b981;
        color: white;
        border: 1px solid #059669;
    }
    .btn-download:hover { background: #059669; }
    
    .btn-video {
        background: #f8fafc;
        color: #334155;
        border: 1px solid #cbd5e1;
    }
    .btn-video:hover { background: #f1f5f9; color: #0f172a; border-color: #94a3b8;}

    .btn-locked {
        background: #f1f5f9;
        color: #94a3b8;
        border: 1px solid #e2e8f0;
        cursor: not-allowed;
    }

    .empty-state { 
        text-align: center; 
        padding: 80px 20px; 
        color: #64748b; 
    }
    
    .btn-std {
        background: #00059E;
        color: white;
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 600;
        transition: background 0.3s;
        text-decoration: none;
        display: inline-block;
    }
    .btn-std:hover {
        background: #00037a;
    }

    @media (max-width: 480px) {
        .orders-grid { grid-template-columns: 1fr; padding: 15px; }
    }
</style>

<div class="account-wrapper">
    <div class="app-header">
        <a href="account" class="btn-back">
            <svg width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>
        </a>
        <h2 class="section-title">My Purchases</h2>
    </div>

    <?php if(empty($all_orders)): ?>
        <div class="empty-state">
            <div style="margin-bottom: 15px; color: #cbd5e1;">
                <svg width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="margin: 0 auto;">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                </svg>
            </div>
            <h3 style="margin: 0 0 10px 0; color: #0f172a; font-weight: 700;">No purchases yet</h3>
            <p style="margin: 0 0 20px 0;">Looks like you haven't bought anything yet.</p>
            <a href="products" class="btn-std">Browse Products</a>
        </div>
    <?php else: ?>
        <div class="orders-grid">
            <?php foreach($all_orders as $o): ?>
            <?php 
                $status_class = strtolower($o['status'] ?? 'pending'); 
                $is_approved = in_array($status_class, ['completed', 'approved']);
            ?>
            <div class="order-card">
                <div class="order-img-wrapper">
                    <?php if(!empty($o['main_image'])): ?>
                        <img src="<?php echo (defined('SITE_URL') ? rtrim(SITE_URL, '/') : '') . '/uploads/products/images/' . htmlspecialchars($o['main_image']); ?>" alt="Product">
                    <?php else: ?>
                        <img src="https://via.placeholder.com/400x225?text=No+Image" alt="No Image">
                    <?php endif; ?>
                    <div class="order-status-badge status-<?php echo $status_class; ?>">
                        <?php echo ucfirst(htmlspecialchars($o['status'] ?? 'Pending')); ?>
                    </div>
                </div>
                
                <div class="order-content">
                    <h3 class="order-title"><?php echo htmlspecialchars($o['title'] ?? 'Unknown Product'); ?></h3>
                    
                    <div class="order-meta">
                        <span>Inv: #<?php echo htmlspecialchars($o['invoice_no']); ?></span>
                        <span class="order-price"><?php echo (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳') . number_format($o['amount'], 2); ?></span>
                    </div>

                    <div class="order-actions">
                        <?php if($is_approved && !empty($o['download_file'])): ?>
                            <a href="<?php echo (defined('SITE_URL') ? rtrim(SITE_URL, '/') : '') . '/uploads/products/files/' . htmlspecialchars($o['download_file']); ?>" download class="btn-action btn-download">
                                <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
                                File
                            </a>
                        <?php else: ?>
                            <span class="btn-action btn-locked" title="Payment pending or file unavailable">
                                <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                                Locked
                            </span>
                        <?php endif; ?>

                        <?php if($is_approved && !empty($o['setup_video_url'])): ?>
                            <a href="<?php echo htmlspecialchars($o['setup_video_url']); ?>" target="_blank" class="btn-action btn-video">
                                <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" /><path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                Setup
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php require_once 'includes/mobile-nav.php'; ?>
