<?php
include "session.php";

require_once __DIR__ . '/../db.php';

require_once 'orders.php'; // للدوال المساعدة

// معالجة حفظ الإعدادات
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_api_settings'])) {
    $company_id = (int)$_POST['company_id'];
    $api_tracking_url = $_POST['api_tracking_url'] ?? '';
    $api_headers = $_POST['api_headers'] ?? '';
    $api_method = $_POST['api_method'] ?? 'GET';
    $api_response_mapping = $_POST['api_response_mapping'] ?? '';
    $api_status_mapping = $_POST['api_status_mapping'] ?? '';
    $api_active = isset($_POST['api_active']) ? 1 : 0;
    
    try {
        $stmt = $pdo->prepare("UPDATE delivery_companies SET 
            api_tracking_url = ?, 
            api_headers = ?, 
            api_method = ?,
            api_response_mapping = ?, 
            api_status_mapping = ?, 
            api_active = ?
            WHERE id = ?");
        $stmt->execute([$api_tracking_url, $api_headers, $api_method, $api_response_mapping, $api_status_mapping, $api_active, $company_id]);
        
        $_SESSION['message'] = "تم تحديث إعدادات API بنجاح";
    } catch (Exception $e) {
        $_SESSION['error'] = "خطأ: " . $e->getMessage();
    }
    
    header("Location: delivery_api_settings.php?company_id=$company_id");
    exit();
}

// جلب قائمة الشركات
$companies = $pdo->query("SELECT * FROM delivery_companies ORDER BY name")->fetchAll();
$selected_id = isset($_GET['company_id']) ? (int)$_GET['company_id'] : ($companies[0]['id'] ?? 0);

// جلب بيانات الشركة المحددة
$company = null;
if ($selected_id) {
    $stmt = $pdo->prepare("SELECT * FROM delivery_companies WHERE id = ?");
    $stmt->execute([$selected_id]);
    $company = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إعدادات API لشركات التوصيل</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #1E40AF;
            --primary-light: #3B82F6;
            --primary-dark: #1E3A8A;
            --success: #059669;
            --success-light: #D1FAE5;
            --danger: #DC2626;
            --danger-light: #FEE2E2;
            --bg: #F1F5F9;
            --surface: #FFFFFF;
            --border: #E2E8F0;
            --text: #0F172A;
            --text-2: #475569;
            --radius: 14px;
            --radius-sm: 8px;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Tajawal', sans-serif; }
        body { background: var(--bg); padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        
        .header {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 20px 24px;
            margin-bottom: 22px;
            border: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 { color: var(--primary); font-size: 22px; font-weight: 900; }
        
        .company-tabs {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 20px;
            background: var(--surface);
            padding: 15px;
            border-radius: var(--radius);
            border: 1px solid var(--border);
        }
        .company-tab {
            padding: 8px 16px;
            border-radius: 30px;
            background: var(--bg);
            color: var(--text-2);
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.2s;
            border: 1px solid var(--border);
        }
        .company-tab:hover { background: var(--primary-light); color: white; }
        .company-tab.active { background: var(--primary); color: white; border-color: var(--primary); }
        
        .card {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 24px;
            border: 1px solid var(--border);
        }
        
        .form-group { margin-bottom: 20px; }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 700;
            font-size: 14px;
            color: var(--text);
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid var(--border);
            border-radius: var(--radius-sm);
            font-size: 14px;
            font-family: 'Tajawal', sans-serif;
            transition: all 0.2s;
        }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            border-color: var(--primary-light);
            outline: none;
            box-shadow: 0 0 0 3px rgba(59,130,246,0.12);
        }
        .form-group small {
            display: block;
            margin-top: 5px;
            color: var(--text-2);
            font-size: 12px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .btn {
            padding: 12px 24px;
            border-radius: var(--radius-sm);
            font-weight: 700;
            cursor: pointer;
            border: none;
            font-family: 'Tajawal', sans-serif;
            font-size: 14px;
            transition: all 0.2s;
        }
        .btn-primary { background: var(--primary); color: white; }
        .btn-primary:hover { background: var(--primary-dark); }
        .btn-success { background: var(--success); color: white; }
        .btn-success:hover { background: #047857; }
        
        .test-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px dashed var(--border);
        }
        
        .test-result {
            margin-top: 15px;
            padding: 15px;
            border-radius: var(--radius-sm);
            background: #F8FAFC;
            border: 1px solid var(--border);
            display: none;
        }
        .test-result.success { background: var(--success-light); border-color: #A7F3D0; color: var(--success); }
        .test-result.error { background: var(--danger-light); border-color: #FECACA; color: var(--danger); }
        
        .message, .error {
            padding: 14px 18px;
            border-radius: var(--radius-sm);
            margin-bottom: 18px;
            font-weight: 600;
        }
        .message { background: var(--success-light); color: var(--success); border: 1px solid #A7F3D0; }
        .error { background: var(--danger-light); color: var(--danger); border: 1px solid #FECACA; }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
        }
        .badge-success { background: var(--success-light); color: var(--success); }
        .badge-warning { background: #FEF3C7; color: #D97706; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>⚙️ إعدادات API لشركات التوصيل</h1>
            <a href="orders.php" class="btn btn-primary">← العودة للطلبات</a>
        </div>
        
        <?php if (isset($_SESSION['message'])): ?>
            <div class="message">✅ <?= htmlspecialchars($_SESSION['message']) ?></div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?>
            <div class="error">❌ <?= htmlspecialchars($_SESSION['error']) ?></div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>
        
        <div class="company-tabs">
            <?php foreach ($companies as $c): ?>
                <a href="?company_id=<?= $c['id'] ?>" class="company-tab <?= $selected_id == $c['id'] ? 'active' : '' ?>">
                    <?= htmlspecialchars($c['name']) ?>
                    <?php if ($c['api_active']): ?>
                        <span class="badge badge-success" style="margin-right: 5px;">✅ مفعل</span>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>
        
        <?php if ($company): ?>
            <div class="card">
                <form method="post">
                    <input type="hidden" name="company_id" value="<?= $company['id'] ?>">
                    
                    <div class="form-group">
                        <label>🔗 رابط تتبع API (استخدم {tracking_code} للمتغير)</label>
                        <input type="text" name="api_tracking_url" value="<?= htmlspecialchars($company['api_tracking_url'] ?? '') ?>" 
                               placeholder="مثال: https://api.example.com/track/{tracking_code}">
                        <small>يمكنك استخدام: {tracking_code}, {tracking_code_raw}, {api_base_url}, {api_token}, {api_id}, {api_secret}</small>
                    </div>
                    
                    <div class="form-group">
                        <label>📋 هيدرات API (JSON)</label>
                        <textarea name="api_headers" rows="5" style="font-family: monospace; direction: ltr;"><?= htmlspecialchars($company['api_headers'] ?? '') ?></textarea>
                        <small>مثال: {"Authorization": "Bearer {api_token}", "Content-Type": "application/json"}</small>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>🔄 طريقة الطلب</label>
                            <select name="api_method">
                                <option value="GET" <?= ($company['api_method'] ?? 'GET') == 'GET' ? 'selected' : '' ?>>GET</option>
                                <option value="POST" <?= ($company['api_method'] ?? '') == 'POST' ? 'selected' : '' ?>>POST</option>
                                <option value="PUT" <?= ($company['api_method'] ?? '') == 'PUT' ? 'selected' : '' ?>>PUT</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>✅ تفعيل API</label>
                            <div style="display: flex; align-items: center; padding-top: 12px;">
                                <label style="display: flex; align-items: center; gap: 10px;">
                                    <input type="checkbox" name="api_active" value="1" <?= $company['api_active'] ? 'checked' : '' ?>>
                                    <span>نعم، تفعيل التتبع التلقائي لهذه الشركة</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>🎯 مسار الحالة في الاستجابة (JSON Path)</label>
                        <input type="text" name="api_response_mapping" value="<?= htmlspecialchars($company['api_response_mapping'] ?? '') ?>" 
                               placeholder="مثال: $.data.status أو $.shipments[0].status">
                        <small>استخدم $. للإشارة إلى جذر JSON. اترك فارغاً للبحث التلقائي.</small>
                    </div>
                    
                    <div class="form-group">
                        <label>🔄 تحويل الحالات (JSON)</label>
                        <textarea name="api_status_mapping" rows="4" style="font-family: monospace;"><?= htmlspecialchars($company['api_status_mapping'] ?? '') ?></textarea>
                        <small>مثال: {"delivered":"delivered","in_transit":"shipped","returned":"returned"}</small>
                    </div>
                    
                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                        <button type="submit" name="update_api_settings" class="btn btn-success">💾 حفظ الإعدادات</button>
                    </div>
                </form>
                
                <div class="test-section">
                    <h3 style="margin-bottom: 15px; color: var(--text);">🧪 اختبار API</h3>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" id="test_tracking" placeholder="أدخل رمز تتبع للاختبار" style="flex: 1; padding: 12px; border: 1.5px solid var(--border); border-radius: var(--radius-sm);">
                        <button class="btn btn-primary" onclick="testApi(<?= $company['id'] ?>)">اختبار</button>
                    </div>
                    <div id="test_result" class="test-result"></div>
                </div>
            </div>
            
            <div style="margin-top: 20px; padding: 20px; background: var(--surface); border-radius: var(--radius); border: 1px solid var(--border);">
                <h3 style="color: var(--text); margin-bottom: 10px;">📌 معلومات الشركة</h3>
                <table style="width: 100%; border-collapse: collapse;">
                    <tr>
                        <td style="padding: 8px; font-weight: 700;">اسم الشركة:</td>
                        <td style="padding: 8px;"><?= htmlspecialchars($company['name']) ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; font-weight: 700;">نوع API:</td>
                        <td style="padding: 8px;"><?= htmlspecialchars($company['api_type'] ?? 'manual') ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; font-weight: 700;">رابط API الأساسي:</td>
                        <td style="padding: 8px; direction: ltr;"><?= htmlspecialchars($company['api_base_url'] ?? '--') ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; font-weight: 700;">API Token:</td>
                        <td style="padding: 8px; font-family: monospace;"><?= $company['api_token'] ? substr($company['api_token'], 0, 20).'...' : '--' ?></td>
                    </tr>
                </table>
            </div>
        <?php else: ?>
            <div class="card" style="text-align: center; padding: 50px;">
                <p style="color: var(--text-2); font-size: 16px;">لا توجد شركات توصيل متاحة</p>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
    function testApi(companyId) {
        let tracking = document.getElementById('test_tracking').value;
        if (!tracking) {
            alert('الرجاء إدخال رمز تتبع');
            return;
        }
        
        let result = document.getElementById('test_result');
        result.style.display = 'block';
        result.className = 'test-result';
        result.innerHTML = '🔄 جاري الاختبار...';
        
        fetch('test_delivery_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'company_id=' + companyId + '&tracking_code=' + encodeURIComponent(tracking)
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                result.className = 'test-result success';
                result.innerHTML = '✅ ' + data.message;
            } else {
                result.className = 'test-result error';
                result.innerHTML = '❌ ' + data.message;
            }
        })
        .catch(e => {
            result.className = 'test-result error';
            result.innerHTML = '❌ خطأ في الاتصال: ' + e.message;
        });
    }
    </script>
</body>
</html>