<?php
require_once __DIR__ . '/../includes/config.php';

// Check if logged in
if (!isLoggedIn()) {
    redirectToLogin();
}

// Get order ID
$order_id = $_GET['id'] ?? null;

if (!$order_id || !is_numeric($order_id)) {
    header('Location: ' . APP_URL . '/admin/orders.php');
    exit;
}

// Get order details
$result = $db->query("
    SELECT o.*, 
           c.first_name, c.last_name, c.email, c.phone, c.address,
           os.name as status_name, os.color as status_color,
           d.name as discount_name, d.type as discount_type, d.value as discount_value
    FROM orders o
    LEFT JOIN clients c ON o.client_id = c.id
    LEFT JOIN order_statuses os ON o.status_id = os.id
    LEFT JOIN discounts d ON o.discount_id = d.id
    WHERE o.id = $order_id
");

if (!$result || $result->num_rows === 0) {
    header('Location: ' . APP_URL . '/admin/orders.php');
    exit;
}

$order = $result->fetch_assoc();

// Get order items
$items_result = $db->query("
    SELECT oi.*, p.name, p.image_path
    FROM order_items oi
    LEFT JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = $order_id
");

$items = [];
while ($item = $items_result->fetch_assoc()) {
    $items[] = $item;
}

// Get comments
$comments_result = $db->query("
    SELECT oc.*, u.name as user_name
    FROM order_comments oc
    LEFT JOIN users u ON oc.user_id = u.id
    WHERE oc.order_id = $order_id
    ORDER BY oc.created_at DESC
");

$comments = [];
while ($comment = $comments_result->fetch_assoc()) {
    $comments[] = $comment;
}

// Calculate total
$subtotal = 0;
foreach ($items as $item) {
    $subtotal += $item['quantity'] * $item['price'];
}

$discount_amount = 0;
if ($order['discount_value']) {
    if ($order['discount_type'] === 'percent') {
        $discount_amount = $subtotal * ($order['discount_value'] / 100);
    } else {
        $discount_amount = $order['discount_value'];
    }
}

$delivery_price = $order['delivery_enabled'] ? $order['delivery_price'] : 0;
$total = $subtotal - $discount_amount + $delivery_price;
?>
<!DOCTYPE html>
<html lang="ro">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview Comandă #<?php echo $order['id']; ?> - <?php echo APP_NAME; ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
        :root{
          --bg:#0E0F11;--bg2:#141517;--bg3:#1A1C1F;--bg4:#222428;
          --border:#2A2D32;--border2:#333740;--text:#F0ECE3;--text2:#9A9590;
          --accent:#D4694A;--accent2:#E8856A;--green:#3DB87A;--red:#E05252;
        }
        html,body{height:100%;background:var(--bg);color:var(--text);font-family:'DM Sans',sans-serif;margin:0;padding:0}
        body{padding:20px}
        
        .container{max-width:1000px;margin:0 auto}
        .header{margin-bottom:30px}
        .back-link{color:var(--accent);text-decoration:none;font-size:13px;margin-bottom:10px;display:inline-block}
        .back-link:hover{color:var(--accent2)}
        
        .order-header{display:flex;justify-content:space-between;align-items:start;margin-bottom:30px;background:var(--bg2);padding:20px;border:1px solid var(--border);border-radius:10px}
        .order-title{font-size:24px;font-weight:700;margin-bottom:10px}
        .order-status{display:inline-block;padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600}
        
        .content{display:grid;grid-template-columns:2fr 1fr;gap:30px;margin-bottom:30px}
        
        .section{background:var(--bg2);padding:20px;border:1px solid var(--border);border-radius:10px}
        .section-title{font-size:16px;font-weight:600;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid var(--border)}
        
        .client-info,.delivery-info{margin-bottom:15px;padding-bottom:15px;border-bottom:1px solid var(--border)}
        .client-info:last-child,.delivery-info:last-child{border-bottom:none;margin-bottom:0;padding-bottom:0}
        
        .info-label{font-size:12px;color:var(--text2);text-transform:uppercase;font-weight:600;margin-bottom:4px}
        .info-value{font-size:14px;color:var(--text)}
        
        .items-list{margin-bottom:0}
        .item{display:flex;gap:15px;padding:15px;background:var(--bg3);border-radius:8px;margin-bottom:10px;border:1px solid var(--border)}
        .item:last-child{margin-bottom:0}
        .item-image{width:80px;height:80px;background:var(--bg);border-radius:6px;overflow:hidden;flex-shrink:0;border:1px solid var(--border);display:flex;align-items:center;justify-content:center}
        .item-image img{width:100%;height:100%;object-fit:cover}
        .item-image-empty{font-size:30px}
        .item-details{flex:1}
        .item-name{font-weight:600;margin-bottom:6px}
        .item-qty{font-size:13px;color:var(--text2)}
        .item-price{text-align:right}
        .item-price-qty{font-size:12px;color:var(--text2);margin-bottom:4px}
        .item-total{font-weight:600;font-size:15px}
        
        .summary{background:var(--bg3);padding:15px;border-radius:8px}
        .summary-row{display:flex;justify-content:space-between;margin-bottom:10px;font-size:13px}
        .summary-row.total{border-top:1px solid var(--border);padding-top:10px;margin-top:10px;font-size:15px;font-weight:600}
        
        .comments-section{grid-column:1/-1}
        .comment{background:var(--bg3);padding:12px;border-radius:8px;margin-bottom:10px;border:1px solid var(--border)}
        .comment:last-child{margin-bottom:0}
        .comment-header{display:flex;justify-content:space-between;margin-bottom:8px}
        .comment-author{font-weight:600;font-size:13px}
        .comment-time{font-size:11px;color:var(--text2)}
        .comment-text{font-size:13px;line-height:1.5}
        
        .add-comment{margin-top:15px}
        .form-group{margin-bottom:10px}
        .form-label{display:block;font-size:12px;font-weight:600;color:var(--text2);margin-bottom:4px;text-transform:uppercase}
        .form-input,.form-textarea{width:100%;padding:10px;background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;font-family:'DM Sans',sans-serif;font-size:13px}
        .form-textarea{resize:vertical;min-height:80px}
        .form-textarea:focus,.form-input:focus{outline:none;border-color:var(--accent)}
        
        .btn{padding:10px 16px;background:var(--accent);color:white;border:none;border-radius:6px;font-weight:600;font-size:13px;cursor:pointer;transition:background 0.15s}
        .btn:hover{background:var(--accent2)}
        .btn-secondary{background:var(--border);color:var(--text)}
        .btn-secondary:hover{background:var(--border2)}
        
        .actions{display:flex;gap:10px;margin-top:20px}
        .actions .btn{flex:1}
        
        @media (max-width:768px) {
            .content{grid-template-columns:1fr}
            .order-header{flex-direction:column}
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="../admin/orders.php" class="back-link">← Înapoi la comenzi</a>
        
        <div class="order-header">
            <div>
                <div class="order-title">Comandă #<?php echo $order['id']; ?></div>
                <span class="order-status" style="background:<?php echo $order['status_color']; ?>20;color:<?php echo $order['status_color']; ?>;border:1px solid <?php echo $order['status_color']; ?>40">
                    <?php echo htmlspecialchars($order['status_name']); ?>
                </span>
            </div>
            <div style="text-align:right;font-size:12px;color:var(--text2)">
                Data: <?php echo formatDate($order['order_date']); ?><br>
                Creat: <?php echo formatDate($order['created_at']); ?>
            </div>
        </div>
        
        <div class="content">
            <!-- Items & Summary -->
            <div>
                <div class="section">
                    <div class="section-title">Produse (<?php echo count($items); ?>)</div>
                    <div class="items-list">
                        <?php foreach ($items as $item): ?>
                            <div class="item">
                                <div class="item-image">
                                    <?php if ($item['image_path'] && file_exists(__DIR__ . '/../uploads/' . $item['image_path'])): ?>
                                        <img src="<?php echo APP_URL . '/uploads/' . urlencode($item['image_path']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>">
                                    <?php else: ?>
                                        <div class="item-image-empty">📦</div>
                                    <?php endif; ?>
                                </div>
                                <div class="item-details">
                                    <div class="item-name"><?php echo htmlspecialchars($item['name']); ?></div>
                                    <div class="item-qty">Cantitate: <?php echo $item['quantity']; ?> x <?php echo formatPrice($item['price']); ?></div>
                                </div>
                                <div class="item-price">
                                    <div class="item-price-qty"></div>
                                    <div class="item-total"><?php echo formatPrice($item['quantity'] * $item['price']); ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="summary" style="margin-top:20px">
                        <div class="summary-row">
                            <span>Subtotal:</span>
                            <span><?php echo formatPrice($subtotal); ?></span>
                        </div>
                        <?php if ($discount_amount > 0): ?>
                            <div class="summary-row" style="color:var(--green)">
                                <span>Reducere <?php echo $order['discount_name']; ?>:</span>
                                <span>-<?php echo formatPrice($discount_amount); ?></span>
                            </div>
                        <?php endif; ?>
                        <?php if ($delivery_price > 0): ?>
                            <div class="summary-row">
                                <span>Livrare:</span>
                                <span><?php echo formatPrice($delivery_price); ?></span>
                            </div>
                        <?php endif; ?>
                        <div class="summary-row total">
                            <span>Total:</span>
                            <span><?php echo formatPrice($total); ?></span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Client Info & Delivery -->
            <div>
                <div class="section">
                    <div class="section-title">Client</div>
                    <div class="client-info">
                        <div class="info-label">Nume</div>
                        <div class="info-value"><?php echo htmlspecialchars(getClientName($order['first_name'], $order['last_name'])); ?></div>
                    </div>
                    <div class="client-info">
                        <div class="info-label">Email</div>
                        <div class="info-value"><?php echo htmlspecialchars($order['email'] ?? '—'); ?></div>
                    </div>
                    <div class="client-info">
                        <div class="info-label">Telefon</div>
                        <div class="info-value"><?php echo htmlspecialchars($order['phone'] ?? '—'); ?></div>
                    </div>
                    
                    <?php if ($order['delivery_enabled']): ?>
                        <div style="margin-top:20px;padding-top:20px;border-top:1px solid var(--border)">
                            <div class="section-title" style="margin-bottom:10px">Livrare</div>
                            <div class="delivery-info">
                                <div class="info-label">Adresă</div>
                                <div class="info-value"><?php echo htmlspecialchars($order['delivery_address'] ?? '—'); ?></div>
                            </div>
                            <div class="delivery-info">
                                <div class="info-label">Cost</div>
                                <div class="info-value"><?php echo formatPrice($delivery_price); ?></div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($order['notes']): ?>
                        <div style="margin-top:20px;padding-top:20px;border-top:1px solid var(--border)">
                            <div class="section-title" style="margin-bottom:10px">Note</div>
                            <div class="info-value"><?php echo htmlspecialchars($order['notes']); ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Comments -->
            <div class="comments-section">
                <div class="section">
                    <div class="section-title">Comentarii (<?php echo count($comments); ?>)</div>
                    
                    <div class="comments-list" style="margin-bottom:20px">
                        <?php if (empty($comments)): ?>
                            <p style="color:var(--text2);font-size:13px">Nu sunt comentarii. Fii primul!</p>
                        <?php else: ?>
                            <?php foreach ($comments as $comment): ?>
                                <div class="comment">
                                    <div class="comment-header">
                                        <span class="comment-author"><?php echo htmlspecialchars($comment['user_name']); ?></span>
                                        <span class="comment-time"><?php echo formatDate($comment['created_at']); ?> <?php echo date('H:i', strtotime($comment['created_at'])); ?></span>
                                    </div>
                                    <div class="comment-text"><?php echo htmlspecialchars($comment['comment']); ?></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <div class="add-comment">
                        <form id="commentForm" method="POST" action="<?php echo APP_URL; ?>/api/add-comment.php">
                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                            <div class="form-group">
                                <label class="form-label">Adaugă comentariu</label>
                                <textarea name="comment" class="form-textarea" placeholder="Scrie un comentariu..." required></textarea>
                            </div>
                            <button type="submit" class="btn">Trimite comentariu</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="actions">
            <a href="<?php echo APP_URL; ?>/admin/orders.php" class="btn btn-secondary" style="text-decoration:none;text-align:center">← Înapoi</a>
        </div>
    </div>

    <script>
        document.getElementById('commentForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const response = await fetch(this.action, {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                location.reload();
            } else {
                alert('Eroare: ' + data.error);
            }
        });
    </script>
</body>
</html>
