<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/includes/db.php';

// Safe user check
$user = $_SESSION['user'] ?? null;
if (!$user) {
    header('Location: login.php');
    exit;
}

// Check pricing view permission
$userRole = $user['role'] ?? '';
$hasPricingPerm = ($userRole === 'admin') || (!empty($user['permissions']['pricing']['view']));
if (!$hasPricingPerm) {
    header('Location: index.php?error=unauthorized');
    exit;
}

// If form_id query param is present, fetch it directly
$preselected_id = isset($_GET['form_id']) ? intval($_GET['form_id']) : 0;
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>تطبيق تسعير الاستمارات | <?php echo htmlspecialchars(getOrgName($conn)); ?></title>
    <!-- Google Fonts: Cairo -->
    <link rel="stylesheet" href="css/cairo.css">
    <!-- Font Awesome for premium icons -->
    <link rel="stylesheet" href="css/fontawesome/css/all.min.css">
    <!-- Custom Style for Mobile App View -->
    <link rel="stylesheet" href="css/order_style.css">
    <script src="js/auth.js?v=<?php echo time(); ?>"></script>
    <style>
        /* Hide navbar/sidebar completely */
        .sidebar, .top-bar, nav.sidebar {
            display: none !important;
        }

        body {
            margin: 0;
            padding: 0;
            background: var(--body-bg) !important;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Cairo', sans-serif;
            overflow: hidden;
            color: var(--text-primary);
        }

        .standalone-app-container {
            width: 100%;
            max-width: 480px;
            height: 100vh;
            max-height: 920px;
            background: var(--device-bg);
            border-radius: 24px;
            box-shadow: var(--shadow-lg);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            border: 1px solid var(--card-border);
            transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        }

        #forms-list-container {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        #pricing-cards-container {
            display: flex;
            flex-direction: column;
            gap: 14px;
        }

        @media (max-width: 767px) {
            .standalone-app-container {
                max-width: 100vw;
                height: 100vh;
                max-height: 100vh;
                border-radius: 0;
                border: none;
            }
        }

        /* Responsive iPad, Tablet & Desktop Layout System */
        @media (min-width: 768px) {
            body {
                padding: 24px 16px;
                align-items: flex-start;
                overflow-y: auto;
            }

            .standalone-app-container {
                max-width: 980px;
                height: auto;
                min-height: 840px;
                border-radius: 24px;
                box-shadow: var(--shadow-lg);
            }

            .status-bar {
                display: none !important;
            }

            .app-header {
                padding: 18px 28px !important;
                border-radius: 23px 23px 0 0;
            }

            .app-content {
                padding: 24px 28px 100px !important;
            }

            /* 2 Columns side-by-side for Open Forms List on iPad */
            #forms-list-container {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 16px;
            }

            /* 2 Columns side-by-side for Material Pricing Cards on iPad */
            #pricing-cards-container {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 16px;
            }

            /* Financial Stats Grid 4 columns side-by-side on iPad */
            .pricing-stats-grid {
                grid-template-columns: repeat(4, 1fr) !important;
                gap: 14px !important;
            }

            .app-nav {
                padding: 10px 28px;
                border-radius: 0 0 23px 23px;
                justify-content: center;
                gap: 40px;
            }

            .nav-item {
                max-width: 160px;
            }
        }

        @media (min-width: 1100px) {
            .standalone-app-container {
                max-width: 1140px;
            }

            #forms-list-container,
            #pricing-cards-container {
                grid-template-columns: repeat(2, 1fr);
                gap: 20px;
            }
        }

        .home-return-btn {
            background: rgba(255, 255, 255, 0.18);
            color: #fff;
            border: none;
            width: 34px;
            height: 34px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            text-decoration: none;
            transition: var(--transition);
        }
        .home-return-btn:hover {
            background: rgba(255, 255, 255, 0.35);
            color: #fff;
        }

        /* Return to forms list button styling */
        .back-to-list-btn {
            background: var(--card-bg);
            color: var(--text-primary);
            border: 1px solid var(--card-border);
            padding: 8px 16px;
            border-radius: 12px;
            font-size: 12.5px;
            font-weight: 700;
            font-family: 'Cairo', sans-serif;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            margin-bottom: 15px;
            transition: all 0.2s ease;
            box-shadow: var(--shadow-sm);
        }
        .back-to-list-btn:hover {
            background: rgba(99, 102, 241, 0.12);
            border-color: var(--primary-color);
            color: var(--primary-color);
            transform: translateX(4px);
        }

        .btn-refresh-cache {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            height: 36px;
            padding: 0 12px;
            border-radius: 18px;
            border: 1px solid var(--card-border);
            background: var(--card-bg);
            color: var(--text-primary);
            font-family: 'Cairo', sans-serif;
            font-size: 11.5px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            white-space: nowrap;
            flex-shrink: 0;
        }
        .btn-refresh-cache:hover {
            transform: scale(1.03);
            border-color: var(--primary-color);
            color: var(--primary-color);
            background: rgba(99, 102, 241, 0.1);
        }
        .btn-refresh-cache:active {
            transform: scale(0.96);
        }

        /* Material Item Pricing Card */
        .material-item-card {
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 16px;
            padding: 16px;
            margin-bottom: 14px;
            box-shadow: var(--shadow-sm);
            transition: all 0.25s ease;
        }
        .material-item-card:hover {
            border-color: rgba(99, 102, 241, 0.4);
            box-shadow: var(--shadow-md);
        }
        .material-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px dashed var(--card-border);
        }
        .material-card-title {
            font-size: 14px;
            font-weight: 800;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .material-qty-badge {
            background: rgba(99, 102, 241, 0.12);
            color: var(--primary-color);
            border: 1px solid rgba(99, 102, 241, 0.25);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
        }

        /* Unit Price Input Field Wrapper & Styles */
        .price-input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            width: 100%;
        }
        .item-price-input {
            width: 100%;
            background: var(--input-bg);
            color: var(--text-primary);
            border: 1.5px solid var(--input-border);
            border-radius: 12px;
            padding: 10px 50px 10px 14px;
            font-size: 16px;
            font-weight: 800;
            font-family: 'Cairo', sans-serif;
            outline: none;
            transition: all 0.2s ease;
            box-sizing: border-box;
        }
        .item-price-input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px var(--input-focus-shadow);
        }
        .price-currency-label {
            position: absolute;
            left: 14px;
            font-size: 12px;
            font-weight: 800;
            color: var(--primary-color);
            pointer-events: none;
            background: rgba(99, 102, 241, 0.12);
            padding: 2px 8px;
            border-radius: 6px;
        }

        .pricing-calc-badge-row {
            margin-top: 10px;
            background: rgba(99, 102, 241, 0.05);
            border: 1px solid var(--card-border);
            border-radius: 10px;
            padding: 8px 12px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 11.5px;
            color: var(--text-secondary);
        }
    </style>
</head>
<body>

<div class="standalone-app-container">
    
    <!-- Status Bar -->
    <div class="status-bar" style="padding: 10px 18px 4px 18px;">
        <div class="status-time" id="status-time">12:00</div>
        <div class="status-icons">
            <i class="fa-solid fa-wifi"></i>
            <i class="fa-solid fa-signal"></i>
            <i class="fa-solid fa-battery-three-quarters"></i>
        </div>
    </div>

    <!-- Main App Frame -->
    <div class="app-mobile-container" style="flex:1; display:flex; flex-direction:column; overflow:hidden;">

        <!-- App Header (Unified with order.php Indigo/Violet theme) -->
        <header class="app-header" style="background: var(--primary-gradient, linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)); padding: 14px 18px;">
            <div class="brand">
                <a href="index.php" class="home-return-btn" title="العودة للوحة التحكم الرئيسية">
                    <i class="fa-solid fa-house"></i>
                </a>
                <div class="brand-text" style="margin-right: 10px;">
                    <h1 style="font-size: 16px;"><?php echo htmlspecialchars(getOrgName($conn)); ?></h1>
                    <span class="subtitle" style="font-size: 11px;">تطبيق تسعير الاستمارات السريع 🏷️</span>
                </div>
            </div>
            <div class="header-action" style="display:flex; align-items:center; gap:8px;">
                <button type="button" class="btn-refresh-cache" id="system-refresh-btn-pricing" onclick="refreshSystemAndClearCache(this)" title="تحديث بيانات السيرفر ومسح الذاكرة المؤقتة (الكاش)">
                    <i class="fa-solid fa-arrows-rotate" id="refresh-cache-icon"></i>
                    <span class="refresh-btn-text">تحديث النظام والكاش</span>
                </button>
                <button id="device-theme-toggle" class="header-icon-btn" title="تغيير المظهر">
                    <i class="fa-solid fa-sun"></i>
                </button>
            </div>
        </header>

        <!-- App Content Sheets Container -->
        <main class="app-content" style="flex:1; overflow-y:auto; padding:16px;">

            <!-- SHEET 1: SELECT FORM SHEET -->
            <section id="sheet-select-form" class="app-sheet active">
                <div class="sheet-title-wrapper">
                    <h2>اختر استمارة لتسعيرها 📋</h2>
                    <p>الاستمارات المفتوحة الموجهة للتسعير حالياً</p>
                </div>

                <!-- Search Field -->
                <div class="app-input-group" style="margin-bottom:15px;">
                    <div class="input-container">
                        <span class="input-icon"><i class="fa-solid fa-magnifying-glass"></i></span>
                        <input type="text" id="form-search-input" placeholder="ابحث باسم الزبون أو رقم الاستمارة..." autocomplete="off">
                    </div>
                </div>

                <!-- Open Forms Scrollable List -->
                <div id="forms-list-container">
                    <div style="text-align:center; padding:40px 20px; color:var(--text-secondary);">
                        <i class="fa-solid fa-spinner fa-spin" style="font-size:24px; margin-bottom:8px;"></i>
                        <p>جاري تحميل الاستمارات المفتوحة...</p>
                    </div>
                </div>
            </section>

            <!-- SHEET 2: PRICE ITEMS SHEET -->
            <section id="sheet-price-items" class="app-sheet">
                <button class="back-to-list-btn" onclick="showSelectFormSheet()">
                    <i class="fa-solid fa-arrow-right"></i> العودة لقائمة الاستمارات
                </button>

                <div class="sheet-title-wrapper">
                    <h2 style="font-size:16px;">الزبون: <span id="pricing-customer-name" style="color:var(--primary-color);">---</span></h2>
                    <p style="font-size:11.5px;">أدخل أسعار المواد أدناه لاحتساب القيمة الكلية للفاتورة تلقائياً</p>
                </div>

                <!-- Hidden Form id -->
                <input type="hidden" id="pricing-form-id" value="0">

                <!-- Pricing Cards list container -->
                <div id="pricing-cards-container">
                    <!-- Cards dynamically rendered -->
                </div>

                <!-- Financial Calculations Stats Grid -->
                <div class="stats-panel pricing-stats-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 15px; margin-bottom: 15px;">
                    <!-- Card 1: Subtotal -->
                    <div class="stat-card" style="padding: 12px 8px;">
                        <span class="stat-value" id="summary-subtotal" style="font-size: 13.5px; font-weight: 800;">0 د.ع</span>
                        <span class="stat-label" style="font-size: 9.5px; font-weight: 700;">مجموع المواد الأساسي</span>
                    </div>
                    <!-- Card 2: Commission -->
                    <div class="stat-card" style="border-color: rgba(245, 158, 11, 0.2); padding: 12px 8px;">
                        <span class="stat-value" id="summary-commission" style="color: #fbbf24; font-size: 13.5px; font-weight: 800;">+0 د.ع</span>
                        <span class="stat-label" style="font-size: 9.5px; font-weight: 700;">عمولة الصندوق</span>
                    </div>
                    <!-- Card 3: Worker Share -->
                    <div class="stat-card" style="border-color: rgba(99, 102, 241, 0.2); padding: 12px 8px;">
                        <span class="stat-value" id="summary-worker-share" style="color: #818cf8; font-size: 13.5px; font-weight: 800;">-0 د.ع</span>
                        <span class="stat-label" style="font-size: 9.5px; font-weight: 700;">أجور وحصص العمال</span>
                    </div>
                    <!-- Card 4: Net Total (Grand Total) -->
                    <div class="stat-card" style="background: var(--primary-gradient); border-color: transparent; padding: 12px 8px;">
                        <span class="stat-value" id="summary-grand-total" style="color: #ffffff; font-size: 14.5px; font-weight: 900;">0 د.ع</span>
                        <span class="stat-label" style="color: rgba(255, 255, 255, 0.85); font-size: 9.5px; font-weight: 700;">المجموع الكلي النهائي</span>
                    </div>
                </div>

                <!-- Save/Submit Button -->
                <button type="button" class="app-submit-btn" id="btn-submit-pricing" style="margin-bottom: 20px; background: var(--primary-gradient);">
                    <span class="btn-text">حفظ وإرسال الأسعار</span>
                    <span class="btn-icon"><i class="fa-solid fa-circle-check"></i></span>
                </button>
            </section>

            <!-- SHEET 3: INFO SHEET -->
            <section id="sheet-info" class="app-sheet">
                <div class="sheet-title-wrapper">
                    <h2>دليل استخدام التسعير 🏷️</h2>
                    <p>معلومات سريعة حول آلية عمل شاشة التسعير السريعة</p>
                </div>

                <div style="background:var(--card-bg); border:1px solid var(--card-border); border-radius:16px; padding:20px; color:var(--text-secondary); line-height:1.7;">
                    <h3 style="color:var(--text-primary); font-size:14px; font-weight:700; margin-bottom:10px;"><i class="fa-solid fa-circle-info" style="margin-left:6px; color:var(--primary-color);"></i>إدخال الأسعار</h3>
                    <p style="font-size:12.5px; margin-bottom:12px;">بمجرد إدخال سعر المفرد لأي مادة، سيقوم النظام تلقائياً وبشكل فوري بحساب المجموع وحصص العمال والعمولات المضافة بناءً على إعدادات المادة.</p>

                    <h3 style="color:var(--text-primary); font-size:14px; font-weight:700; margin-bottom:10px;"><i class="fa-solid fa-arrows-spin" style="margin-left:6px; color:var(--success-color);"></i>التحديث التلقائي</h3>
                    <p style="font-size:12.5px; margin-bottom:12px;">شاشة اختيار الاستمارات تحدث نفسها تلقائياً وبصمت كل 5 ثوانٍ في الخلفية لتظهر أي استمارات جديدة فور إنشائها.</p>

                    <h3 style="color:var(--text-primary); font-size:14px; font-weight:700; margin-bottom:10px;"><i class="fa-solid fa-history" style="margin-left:6px; color:#fbbf24;"></i>سجل التدقيق</h3>
                    <p style="font-size:12.5px;">كل عملية تسعير يتم توثيقها بالكامل في سجل تدقيق العمليات لتوضيح هوية المسعر وقيم التعديل.</p>
                </div>
            </section>

        </main>

        <!-- App Bottom Navigation Bar -->
        <nav class="app-nav">
            <button class="nav-item active" data-target="sheet-select-form">
                <i class="fa-solid fa-list-check nav-icon"></i>
                <span class="nav-label">الاستمارات</span>
            </button>

            <button class="nav-item" data-target="sheet-price-items" id="nav-pricing-tab" style="display:none;">
                <i class="fa-solid fa-tag nav-icon"></i>
                <span class="nav-label">التسعير</span>
            </button>

            <button class="nav-item" data-target="sheet-info">
                <i class="fa-solid fa-info-circle nav-icon"></i>
                <span class="nav-label">نبذة</span>
            </button>
        </nav>

        <!-- Fullscreen Success Overlay -->
        <div class="success-overlay" id="success-overlay">
            <div class="success-card">
                <div class="success-checkmark">
                    <div class="check-icon">
                        <span class="icon-line line-tip"></span>
                        <span class="icon-line line-long"></span>
                        <div class="icon-circle"></div>
                        <div class="icon-fix"></div>
                    </div>
                </div>
                <h2>تم حفظ التسعير بنجاح!</h2>
                <p>تم تحديث قيم الفاتورة وترحيل الأرباح وعمولات الصناديق.</p>

                <div class="success-details" style="background:rgba(255,255,255,0.06); border-radius:12px; padding:12px; width:100%; text-align:right;">
                    <div class="detail-row">
                        <span class="detail-label" style="opacity:0.7;">الزبون:</span>
                        <span class="detail-value" id="confirm-customer" style="font-weight:700;">---</span>
                    </div>
                    <div class="detail-row" style="margin-top:6px;">
                        <span class="detail-label" style="opacity:0.7;">المجموع النهائي:</span>
                        <span class="detail-value" id="confirm-total" style="font-weight:700; color:#34d399;">---</span>
                    </div>
                </div>

                <button class="btn-success-close" id="btn-success-close">إغلاق والعودة للقائمة</button>
            </div>
        </div>

    </div>

</div>

<script>
    const PRESELECTED_FORM_ID = <?php echo $preselected_id; ?>;
</script>
<!-- Custom JavaScript for Mobile App Interaction -->
<script src="js/pricing.js?v=<?php echo time(); ?>"></script>
</body>
</html>

