<?php
// ========================================
// جزئیات سفارش
// پروژه فروشگاه کیف‌لند
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'جزئیات سفارش';

$order_id = intval($_GET['id'] ?? 0);
if (!$order_id) { header('Location: orders.php'); exit; }

$stmt = $db->prepare("SELECT o.*, u.full_name, u.email, u.phone FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
$stmt->execute([$order_id]);
$order = $stmt->fetch();

if (!$order) { header('Location: orders.php'); exit; }

$items = $db->prepare("SELECT * FROM order_items WHERE order_id = ? ORDER BY id ASC");
$items->execute([$order_id]);
$items = $items->fetchAll();

$logs = $db->prepare("SELECT * FROM activity_logs WHERE description LIKE ? ORDER BY created_at DESC LIMIT 10");
$logs->execute(["%سفارش #$order_id%"]);
$logs = $logs->fetchAll();

$success = ''; $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order'])) {
    $status = $_POST['status'] ?? $order['status'];
    $tracking = trim($_POST['tracking_code'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    try {
        $sql = "UPDATE orders SET status = ?, notes = ?, updated_at = NOW()";
        $params = [$status, $notes];
        if ($status === 'shipped' && !empty($tracking)) { $sql .= ", tracking_code = ?, shipped_at = NOW()"; $params[] = $tracking; }
        elseif ($status === 'delivered') { $sql .= ", delivered_at = NOW()"; }
        elseif ($status === 'cancelled') { $sql .= ", cancelled_at = NOW()"; }
        
        $sql .= " WHERE id = ?";
        $params[] = $order_id;
        $db->prepare($sql)->execute($params);
        Auth::logActivity('order_detail_update', "به‌روزرسانی سفارش #$order_id");
        $success = 'سفارش با موفقیت به‌روز شد';
        $stmt->execute([$order_id]);
        $order = $stmt->fetch();
    } catch (Exception $e) { $error = 'خطا: ' . $e->getMessage(); }
}

$status_steps = ['pending', 'processing', 'shipped', 'delivered'];
$current_step = array_search($order['status'], $status_steps);
if ($current_step === false) $current_step = 4; // cancelled/refunded

include 'includes/admin-header.php';
?>

<div class="overlay" id="overlay"></div>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box"><i class="fas fa-search"></i><input type="text" placeholder="جستجو در جزئیات..."></div>
        <div class="header-actions">
            <a href="orders.php" class="btn-secondary"><i class="fas fa-arrow-right"></i> بازگشت به لیست</a>
            <a href="invoice.php?id=<?= $order_id ?>" target="_blank" class="btn-secondary"><i class="fas fa-print"></i> چاپ فاکتور</a>
        </div>
    </header>

    <div class="dashboard-content page-orders">
        <div class="page-title"><h1>سفارش #<?= htmlspecialchars($order['order_number']) ?></h1><p>ثبت شده در <?= jdate($order['created_at']) ?></p></div>

        <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

        <div class="content-grid">
            <!-- وضعیت و تایم‌لاین -->
            <div class="glass-card" style="grid-column: span 2;">
                <div class="card-header"><h2>وضعیت سفارش</h2></div>
                <div class="order-status-timeline">
                    <?php foreach ($status_steps as $i => $step): ?>
                    <div class="timeline-step <?= $i < $current_step ? 'completed' : ($i == $current_step ? 'active' : '') ?>">
                        <div class="timeline-dot"><?= $i < $current_step ? '<i class="fas fa-check"></i>' : ($i + 1) ?></div>
                        <span><?= getStatusText($step) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <form method="POST" class="form-grid" style="margin-top:20px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));">
                    <div class="form-group"><label class="form-label">تغییر وضعیت</label>
                        <select name="status" class="form-select">
                            <?php foreach (['pending','processing','shipped','delivered','cancelled'] as $s): ?><option value="<?= $s ?>" <?= $order['status']==$s?'selected':'' ?>><?= getStatusText($s) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group"><label class="form-label">کد رهگیری پست</label><input type="text" name="tracking_code" class="form-input" value="<?= htmlspecialchars($order['tracking_code'] ?? '') ?>"></div>
                    <div class="form-group"><label class="form-label">یادداشت مدیر</label><textarea name="notes" class="form-textarea" rows="1"><?= htmlspecialchars($order['notes'] ?? '') ?></textarea></div>
                    <div style="display:flex; align-items:flex-end;"><button type="submit" name="update_order" class="btn btn-primary" style="width:100%;"><i class="fas fa-save"></i> ذخیره تغییرات</button></div>
                </form>
            </div>

            <!-- اطلاعات مشتری -->
            <div class="glass-card">
                <div class="card-header"><h2>اطلاعات مشتری</h2></div>
                <div style="line-height:1.8; font-size:13px;">
                    <p><strong>نام:</strong> <?= $order['full_name'] ? htmlspecialchars($order['full_name']) : 'مهمان' ?></p>
                    <p><strong>ایمیل:</strong> <?= htmlspecialchars($order['email'] ?? '-') ?></p>
                    <p><strong>تلفن تماس:</strong> <?= htmlspecialchars($order['shipping_phone'] ?? $order['phone'] ?? '-') ?></p>
                    <p><strong>آدرس ارسال:</strong> <?= nl2br(htmlspecialchars($order['shipping_address'] ?? 'ثبت نشده')) ?></p>
                    <p><strong>شهر / کد پستی:</strong> <?= htmlspecialchars($order['shipping_city'] ?? '-') ?> / <?= htmlspecialchars($order['shipping_postal_code'] ?? '-') ?></p>
                </div>
            </div>

            <!-- خلاصه مالی -->
            <div class="glass-card">
                <div class="card-header"><h2>خلاصه مالی</h2></div>
                <div class="revenue-summary">
                    <div class="revenue-item"><div class="revenue-label">مبلغ کل کالاها</div><div class="revenue-value"><?= formatPrice($order['total_amount']) ?></div></div>
                    <?php if ($order['discount_amount'] > 0): ?><div class="revenue-item" style="border-color:var(--success);"><div class="revenue-label">تخفیف</div><div class="revenue-value text-success">-<?= formatPrice($order['discount_amount']) ?></div></div><?php endif; ?>
                    <div class="revenue-item"><div class="revenue-label">هزینه ارسال</div><div class="revenue-value"><?= $order['shipping_cost'] > 0 ? formatPrice($order['shipping_cost']) : 'رایگان' ?></div></div>
                    <div class="revenue-item"><div class="revenue-label">مالیات (<?= $order['tax_amount'] > 0 ? number_format(($order['tax_amount']/$order['total_amount'])*100, 1) : '0' ?>٪)</div><div class="revenue-value"><?= formatPrice($order['tax_amount']) ?></div></div>
                    <div class="revenue-item" style="background:rgba(0,122,255,0.15); border-color:rgba(0,122,255,0.3);"><div class="revenue-label">مبلغ نهایی پرداختی</div><div class="revenue-value" style="color:var(--primary);"><?= formatPrice($order['final_amount']) ?></div></div>
                    <div style="margin-top:8px;"><span class="status <?= $order['payment_status']=='paid'?'success':'pending' ?>" style="font-size:11px; padding:6px 10px;"><?= getStatusText($order['payment_status']) ?></span></div>
                </div>
            </div>

            <!-- لیست آیتم‌ها -->
            <div class="glass-card" style="grid-column: span 2;">
                <div class="card-header"><h2>اقلام سفارش</h2><span class="badge badge-info"><?= count($items) ?> قلم</span></div>
                <div class="table-container">
                    <table class="data-table">
                        <thead><tr><th>محصول</th><th>تعداد</th><th>قیمت واحد</th><th>تخفیف</th><th>جمع جزء</th></tr></thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($item['product_name']) ?></strong><?php if($item['product_sku']): ?><br><small style="color:var(--text-secondary);">SKU: <?= htmlspecialchars($item['product_sku']) ?></small><?php endif; ?></td>
                                <td><?= number_format($item['quantity']) ?></td>
                                <td><?= formatPrice($item['price']) ?></td>
                                <td><?= $item['discount'] > 0 ? formatPrice($item['discount']) : '-' ?></td>
                                <td><strong><?= formatPrice($item['subtotal']) ?></strong></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- لاگ فعالیت‌ها -->
            <div class="glass-card">
                <div class="card-header"><h2>تاریخچه فعالیت‌ها</h2></div>
                <div class="activities-list" style="max-height:300px; overflow-y:auto;">
                    <?php if (!empty($logs)): ?>
                        <?php foreach ($logs as $log): ?>
                        <div class="activity-item">
                            <div class="activity-icon blue"><i class="fas fa-history"></i></div>
                            <div class="activity-info"><h4><?= htmlspecialchars($log['action']) ?></h4><p><?= timeAgo($log['created_at']) ?> | <?= htmlspecialchars($log['ip_address']) ?></p></div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?><p style="text-align:center; padding:20px; color:var(--text-secondary);">فعلاً فعالیتی ثبت نشده است.</p><?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="assets/js/script.js"></script>
<?php include 'includes/admin-footer.php'; ?>