<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Red Talent — My Orders</title>
    <script src="https://my-perspolis.com/storage/app/public/3.4.17"></script>
    <link href="https://my-perspolis.com/storage/app/public/css2.css" rel="stylesheet"/>
    <link href="https://my-perspolis.com/storage/app/public/css22.css" rel="stylesheet"/>
    <script src="https://my-perspolis.com/storage/app/public/react.development.js" crossorigin="anonymous"></script>
    <script src="https://my-perspolis.com/storage/app/public//react-dom.development.js" crossorigin="anonymous"></script>
    <script src="https://my-perspolis.com/storage/app/public/babel.min.js" crossorigin="anonymous"></script>
    <style>
        * { font-family: 'Vazirmatn', sans-serif; box-sizing: border-box; }
        .ms { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0,'wght' 400,'GRAD' 0,'opsz' 24; font-weight: normal; font-style: normal; line-height: 1; letter-spacing: normal; text-transform: none; white-space: nowrap; word-wrap: normal; direction: ltr; -webkit-font-feature-settings: 'liga'; font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; user-select: none; }
        .ms-fill { font-variation-settings: 'FILL' 1,'wght' 400,'GRAD' 0,'opsz' 24; }
        .hide-sb::-webkit-scrollbar { display: none; }
        .hide-sb { -ms-overflow-style: none; scrollbar-width: none; }
        @keyframes fadeUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }
        .fade-up { animation: fadeUp 0.3s ease both; }
        html { min-height: 100%; }
        .app-page { min-height: 100vh; min-height: 100dvh; margin: 0; background: #eef2f7; }
        .app-shell { width: 100%; min-height: 100vh; min-height: 100dvh; padding: 24px; display: grid; place-items: center; }
        .app-container { position: relative; width: min(100%, 430px); height: min(844px, calc(100vh - 48px)); overflow: hidden; background: #F5F7FA; border-radius: 28px; box-shadow: 0 28px 80px rgba(15, 23, 42, 0.22); }
        .app-container button, .app-container a { transition-property: translate, transform, opacity; transition-duration: 180ms; }
        @media (hover: hover) { .app-container button:not(:disabled):hover, .app-container a:not(:disabled):hover { translate: 0 -1px; } }
        @media (max-width: 640px) { .app-shell { padding: 0; } .app-container { width: 100vw; height: 100vh; height: 100dvh; border-radius: 0; box-shadow: none; } }
    </style>
</head>
<body class="app-page">
<div id="root"></div>

@verbatim
    <script type="text/babel">
        const { useState, useEffect } = React;

        const Ico = ({ n, fill=false, size=24, cls='', style={} }) => (
            <span className={`ms ${fill?'ms-fill':''} ${cls}`} style={{fontSize:size,lineHeight:1,...style}}>{n}</span>
        );

        const toJalali = (dateString) => {
            if (!dateString) return 'نامشخص';
            try {
                const justDate = dateString.split(' ')[0].replace(/-/g, '/');
                const date = new Date(justDate);
                if (isNaN(date.getTime())) return dateString;
                return new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: 'long', day: 'numeric' }).format(date);
            } catch (e) { return dateString; }
        };

        const OrdersScreen = () => {
            const [orders, setOrders] = useState([]);
            const [loading, setLoading] = useState(true);
            const [selectedOrder, setSelectedOrder] = useState(null);
            const [payingInstallment, setPayingInstallment] = useState(null);

            useEffect(() => {
                fetch('/api/my-orders', { headers: { 'Accept': 'application/json' } })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) setOrders(data.orders || []);
                        setLoading(false);
                    })
                    .catch(err => { console.error(err); setLoading(false); });
            }, []);

            const handleLogout = () => document.getElementById('logout-form').submit();

            const handleInstallmentPay = async (installmentId) => {
                setPayingInstallment(installmentId);
                try {
                    const res = await fetch('/api/installment/pay', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        },
                        body: JSON.stringify({ installment_id: installmentId })
                    });
                    const data = await res.json();

                    if (data.success && data.gateway_url) {
                        window.location.href = data.gateway_url;
                    } else {
                        alert(data.message || 'خطا در اتصال به درگاه');
                        setPayingInstallment(null);
                    }
                } catch (e) {
                    alert('خطا در ارتباط با سرور');
                    setPayingInstallment(null);
                }
            };

            const getStatusBadge = (status) => {
                switch(status) {
                    case 'active': return { text: 'ثبت‌نام فعال', color: '#2E7D32', bg: '#e8f5e9', icon: 'check_circle' };
                    case 'pending_payment': return { text: 'در انتظار پرداخت', color: '#E65100', bg: '#fff3e0', icon: 'hourglass_empty' };
                    case 'cancelled': return { text: 'لغو شده', color: '#C62828', bg: '#ffebee', icon: 'cancel' };
                    default: return { text: 'نامشخص', color: '#486581', bg: '#f1f5f8', icon: 'help_outline' };
                }
            };

            const getInstallmentBadge = (status) => {
                switch(status) {
                    case 'paid': return { text: 'پرداخت شده', color: '#2E7D32', bg: '#e8f5e9' };
                    case 'pending': return { text: 'در انتظار پرداخت', color: '#102A43', bg: '#f1f5f8' };
                    case 'overdue': return { text: 'سررسید گذشته', color: '#C62828', bg: '#ffebee' };
                    default: return { text: status, color: '#486581', bg: '#f1f5f8' };
                }
            };

            return (
                <div className="absolute inset-0 bg-[#F5F7FA] flex flex-col fade-up">
                    <form id="logout-form" action="/logout" method="POST" style={{ display: 'none' }}>
                        <input type="hidden" name="_token" value={document.querySelector('meta[name="csrf-token"]').content} />
                    </form>

                    <header className="h-14 bg-white border-b border-gray-100 shadow-sm flex items-center justify-between px-4 shrink-0 z-30">
                        <div className="w-10"></div>
                        <h1 className="font-bold text-sm text-[#102A43]">سفارشات من</h1>
                        <button onClick={() => window.location.href = '/dashboard'} className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-50">
                            <Ico n="arrow_forward" style={{color:'#D32F2F'}}/>
                        </button>
                    </header>

                    <div className="flex-1 overflow-y-auto hide-sb pb-24 px-4 pt-5">
                        {loading ? (
                            <div className="flex flex-col items-center justify-center py-20 gap-3">
                                <div className="w-8 h-8 border-4 border-[#D32F2F] border-t-transparent rounded-full animate-spin"></div>
                            </div>
                        ) : orders.length === 0 ? (
                            <div className="flex flex-col items-center justify-center py-20 gap-4 fade-up">
                                <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center">
                                    <Ico n="receipt_long" size={32} style={{color:'#aaa'}}/>
                                </div>
                                <p className="font-bold text-sm text-[#486581]">شما هیچ سفارشی ندارید.</p>
                            </div>
                        ) : (
                            <div className="flex flex-col gap-4">
                                {orders.map((order, i) => {
                                    const badge = getStatusBadge(order.status);
                                    return (
                                        <div key={order.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden fade-up" style={{animationDelay: `${i * 0.05}s`}}>
                                            <div className="relative h-32 bg-gray-200 w-full">
                                                {order.school_cover ? (
                                                    <img src={`/storage/app/public/${order.school_cover}`} alt={order.school_name} className="w-full h-full object-cover"/>
                                                ) : (
                                                    <div className="w-full h-full bg-gradient-to-tr from-[#102A43] to-[#486581]"></div>
                                                )}
                                                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"/>
                                                <div className="absolute top-3 right-3 bg-white/95 px-2.5 py-1 rounded-full"><span className="text-[10px] font-black text-[#102A43]">کد: #{order.id}</span></div>
                                                <div className="absolute bottom-3 right-3">
                                                    <span className="text-[11px] font-black px-2.5 py-0.5 rounded-lg backdrop-blur-sm bg-black/50 text-white border border-white/20">{order.school_name}</span>
                                                </div>
                                                <div className="absolute bottom-3 left-3">
                                                    <div className="flex items-center gap-1 px-2.5 py-0.5 rounded-lg backdrop-blur-sm border" style={{ backgroundColor: badge.bg, borderColor: badge.color + '50' }}>
                                                        <span className="text-[10px] font-bold" style={{color: badge.color}}>{badge.text}</span>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="p-4">
                                                <div className="flex items-start justify-between gap-2 mb-3">
                                                    <div>
                                                        <h3 className="font-bold text-sm text-[#102A43] mb-1">{order.pack_name}</h3>
                                                        <span className="text-[#486581] text-[11px]">ثبت‌نام: {order.created_at ? toJalali(order.created_at) : order.formatted_date}</span>
                                                    </div>
                                                    <div className="text-left shrink-0 flex flex-col items-end">
                                                        <span className="block text-xs font-black text-[#D32F2F]">{order.formatted_price}</span>
                                                    </div>
                                                </div>

                                                <div className="flex gap-2 mt-4 pt-4 border-t border-gray-100">
                                                    <button onClick={() => setSelectedOrder(order)} className="flex-1 h-11 bg-gray-100 text-[#102A43] rounded-xl text-xs font-bold hover:bg-gray-200 active:scale-[0.98] transition-transform flex items-center justify-center gap-1.5">
                                                        <Ico n="receipt_long" size={16} /> فاکتور و جزییات سفارش
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>

                    {/* Modal */}
                    {selectedOrder && (
                        <div className="absolute inset-0 z-50 flex items-end sm:items-center justify-center">
                            <div className="absolute inset-0 bg-[#102A43]/40 backdrop-blur-sm" onClick={() => setSelectedOrder(null)}></div>

                            <div className="bg-white w-full sm:w-[85%] max-h-[85%] rounded-t-3xl sm:rounded-3xl flex flex-col relative z-10 fade-up overflow-hidden shadow-2xl">
                                <div className="flex justify-between items-center p-5 border-b border-gray-100 bg-white shrink-0">
                                    <div>
                                        <h3 className="font-black text-[#102A43] text-sm">فاکتور سفارش #{selectedOrder.id}</h3>
                                        <p className="text-[10px] text-[#486581]">{selectedOrder.school_name}</p>
                                    </div>
                                    <button onClick={() => setSelectedOrder(null)} className="w-8 h-8 flex items-center justify-center bg-gray-100 rounded-full hover:bg-gray-200">
                                        <Ico n="close" size={18} />
                                    </button>
                                </div>

                                <div className="overflow-y-auto hide-sb p-5 flex flex-col gap-4">

                                    {/* Invoice Card */}
                                    <div className="bg-white border border-gray-100 rounded-2xl p-4 flex flex-col gap-0 shadow-sm">
                                        <div className="flex justify-between items-center pb-2">
                                            <span className="text-xs text-[#486581]">پکیج آموزشی:</span>
                                            <span className="text-xs font-bold text-[#102A43]">{selectedOrder.pack_name}</span>
                                        </div>

                                        {/* Pack Base Price */}
                                        <div className="flex justify-between items-center pb-2 border-b border-gray-50">
                                            <span className="text-[11px] text-[#486581]">هزینه پایه دوره:</span>
                                            <span className="text-[11px] font-bold text-[#102A43]">{parseFloat(selectedOrder.pack_price).toLocaleString()} تومان</span>
                                        </div>

                                        {/* Products List */}
                                        {selectedOrder.products && selectedOrder.products.length > 0 && (
                                            <div className="pt-3 pb-2 border-b border-gray-50">
                                                <span className="text-[11px] font-black text-[#486581] mb-2 block flex items-center gap-1">
                                                    <Ico n="shopping_bag" size={14} /> تجهیزات خریداری شده:
                                                </span>
                                                <div className="flex flex-col gap-2">
                                                    {selectedOrder.products.map((p, idx) => (
                                                        <div key={idx} className="flex justify-between items-center">
                                                            <span className="text-[11px] text-[#102A43] flex items-center gap-1.5">
                                                                <div className="w-1.5 h-1.5 bg-gray-300 rounded-full"></div> {p.name}
                                                            </span>
                                                            <span className="text-[11px] font-bold text-[#102A43]">{parseFloat(p.price).toLocaleString()} تومان</span>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {/* Discount / Voucher */}
                                        {selectedOrder.discount_amount > 0 && (
                                            <div className="flex justify-between items-center pt-3 pb-2 border-b border-gray-50 text-green-600">
                                                <span className="text-[11px] font-bold flex items-center gap-1">
                                                    <Ico n="local_activity" size={14} /> تخفیف اعمال شده:
                                                </span>
                                                <span className="text-[11px] font-black">- {parseFloat(selectedOrder.discount_amount).toLocaleString()} تومان</span>
                                            </div>
                                        )}

                                        {/* Total Price */}
                                        <div className="flex justify-between items-center pt-3">
                                            <span className="text-xs font-black text-[#102A43]">مبلغ نهایی فاکتور:</span>
                                            <span className="text-sm font-black text-[#D32F2F]">{selectedOrder.formatted_price}</span>
                                        </div>
                                    </div>

                                    {/* Dates Info */}
                                    <div className="flex gap-2">
                                        {selectedOrder.start_time && (
                                            <div className="flex-1 bg-blue-50/50 border border-blue-100 rounded-xl p-3 flex flex-col gap-1 items-center justify-center">
                                                <span className="text-[10px] text-blue-600 font-bold">تاریخ شروع دوره</span>
                                                <span className="text-xs font-black text-[#102A43]">{toJalali(selectedOrder.start_time)}</span>
                                            </div>
                                        )}
                                        {selectedOrder.end_time && (
                                            <div className="flex-1 bg-red-50/50 border border-red-100 rounded-xl p-3 flex flex-col gap-1 items-center justify-center">
                                                <span className="text-[10px] text-[#D32F2F] font-bold">تاریخ پایان دوره</span>
                                                <span className="text-xs font-black text-[#102A43]">{toJalali(selectedOrder.end_time)}</span>
                                            </div>
                                        )}
                                    </div>

                                    {/* SCHEDULES SECTION */}
                                    {selectedOrder.schedules && selectedOrder.schedules.length > 0 && (
                                        <div className="bg-[#F5F7FA] rounded-2xl p-3 border border-gray-100">
                                            <p className="text-[10px] font-black text-[#486581] uppercase tracking-widest mb-3 px-1">برنامه کلاسی (سانس‌ها)</p>
                                            <div className="flex flex-col gap-2">
                                                {selectedOrder.schedules.map((sch, idx) => (
                                                    <div key={idx} className="flex items-center justify-between bg-white px-3 py-2.5 rounded-xl border border-gray-100 shadow-sm">
                                                        <div className="flex items-center gap-2.5">
                                                            <div className="w-7 h-7 rounded-lg bg-[#fff0ef] flex items-center justify-center">
                                                                <Ico n="event" size={14} style={{color:'#D32F2F'}} />
                                                            </div>
                                                            <span className="text-xs font-bold text-[#102A43]">{sch.day_name}</span>
                                                        </div>
                                                        <div className="text-xs font-bold text-[#486581] flex items-center gap-1.5" dir="ltr">
                                                            <span className="bg-gray-50 px-2 py-0.5 rounded-md">{sch.start_time_short}</span>
                                                            <span className="text-gray-400 font-normal">-</span>
                                                            <span className="bg-gray-50 px-2 py-0.5 rounded-md">{sch.end_time_short}</span>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    {/* INSTALLMENTS SECTION */}
                                    {selectedOrder.installments && selectedOrder.installments.length > 0 && (
                                        <div className="bg-[#fff8f7] rounded-2xl p-4 border border-[#ffe5e3]">
                                            <p className="text-[11px] font-black text-[#D32F2F] mb-3 flex items-center gap-1.5">
                                                <Ico n="payments" size={16} /> وضعیت اقساط (BNPL)
                                            </p>

                                            <div className="flex flex-col gap-3 relative">
                                                {/* Connecting line */}
                                                <div className="absolute right-[11px] top-4 bottom-4 w-px bg-[#ffcdd2]"></div>

                                                {selectedOrder.installments.map((inst, idx) => {
                                                    const instBadge = getInstallmentBadge(inst.status);
                                                    const isPending = inst.status === 'pending' || inst.status === 'overdue';

                                                    return (
                                                        <div key={inst.id} className="relative pl-2 pr-8">
                                                            {/* Timeline Dot */}
                                                            <div className={`absolute right-1 top-2 w-5 h-5 rounded-full border-2 flex items-center justify-center bg-white ${inst.status === 'paid' ? 'border-[#2E7D32]' : isPending ? 'border-[#D32F2F]' : 'border-gray-300'}`}>
                                                                {inst.status === 'paid' && <div className="w-2.5 h-2.5 bg-[#2E7D32] rounded-full"></div>}
                                                            </div>

                                                            <div className="bg-white rounded-xl p-3 border border-gray-100 shadow-sm flex flex-col gap-2">
                                                                <div className="flex justify-between items-center">
                                                                    <span className="font-bold text-xs text-[#102A43]">قسط {inst.installment_number}</span>
                                                                    <span className="text-[10px] px-2 py-0.5 rounded-md font-bold" style={{backgroundColor: instBadge.bg, color: instBadge.color}}>
                                                                        {instBadge.text}
                                                                    </span>
                                                                </div>
                                                                <div className="flex justify-between items-end mt-1">
                                                                    <div className="flex flex-col">
                                                                        <span className="text-[10px] text-[#486581]">سررسید:</span>
                                                                        <span className="text-xs font-bold text-[#102A43]">{toJalali(inst.due_date)}</span>
                                                                    </div>
                                                                    <div className="text-left flex flex-col items-end gap-1.5">
                                                                        <span className="font-black text-[#D32F2F] text-sm">
                                                                            {parseFloat(inst.amount).toLocaleString()} <span className="text-[10px] font-normal">تومان</span>
                                                                        </span>

                                                                        {/* Pay Button for Pending Installments */}
                                                                        {isPending && (
                                                                            <button
                                                                                onClick={() => handleInstallmentPay(inst.id)}
                                                                                disabled={payingInstallment === inst.id}
                                                                                className="h-7 px-4 bg-[#D32F2F] text-white rounded-lg text-[10px] font-bold active:scale-95 transition-transform disabled:opacity-70 flex items-center gap-1"
                                                                            >
                                                                                {payingInstallment === inst.id ? 'صبر کنید...' : 'پرداخت آنلاین'}
                                                                            </button>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            );
        };

        const App = () => (
            <div className="app-shell">
                <div className="app-container">
                    <div className="absolute inset-0 overflow-hidden">
                        <OrdersScreen />
                    </div>
                </div>
            </div>
        );

        ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
    </script>
@endverbatim
</body>
</html>
