<?php
/**
 * Invoice & Seller Credentials Diagnostic Tool
 * فحص الفواتير وبيانات اعتماد البائعين
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// Database connection
$host = 'localhost';
$dbname = 'jopython24_posf';
$username = 'jopython24_posf';
$password = '@*^0l+]HXGklo79M';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Database connection failed: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$result = [
    'success' => true,
    'timestamp' => date('Y-m-d H:i:s'),
    'diagnostic' => []
];

// 1. Get all sellers with credential info
$stmt = $pdo->query("
    SELECT 
        id,
        seller_name,
        username,
        tax_number,
        income_number,
        client_id,
        secret_key,
        LENGTH(client_id) as client_id_length,
        LENGTH(secret_key) as secret_key_length,
        created_at
    FROM sellers
    ORDER BY created_at DESC
");
$sellers = $stmt->fetchAll(PDO::FETCH_ASSOC);

$result['diagnostic']['all_sellers'] = [];
foreach ($sellers as $seller) {
    $isValid = $seller['client_id_length'] > 30 && $seller['secret_key_length'] > 100;
    $result['diagnostic']['all_sellers'][] = [
        'id' => $seller['id'],
        'seller_name' => $seller['seller_name'],
        'username' => $seller['username'],
        'tax_number' => $seller['tax_number'],
        'income_number' => $seller['income_number'],
        'client_id_preview' => substr($seller['client_id'], 0, 20) . '...',
        'client_id_length' => (int)$seller['client_id_length'],
        'secret_key_length' => (int)$seller['secret_key_length'],
        'credentials_valid' => $isValid,
        'status' => $isValid ? '✅ صالحة' : '❌ غير صالحة (قصيرة جداً)'
    ];
}

// 2. Get recent invoices with their seller info
$stmt = $pdo->query("
    SELECT 
        i.id as invoice_id,
        i.invoice_number,
        i.invoice_date,
        i.status,
        i.total_amount,
        i.seller_id,
        i.created_at,
        s.seller_name,
        s.tax_number,
        LENGTH(s.client_id) as seller_client_id_length,
        LENGTH(s.secret_key) as seller_secret_key_length
    FROM invoices i
    LEFT JOIN sellers s ON i.seller_id = s.id
    ORDER BY i.created_at DESC
    LIMIT 10
");
$invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

$result['diagnostic']['recent_invoices'] = [];
foreach ($invoices as $inv) {
    $credentialsOk = $inv['seller_client_id_length'] > 30 && $inv['seller_secret_key_length'] > 100;
    $result['diagnostic']['recent_invoices'][] = [
        'invoice_number' => $inv['invoice_number'],
        'invoice_date' => $inv['invoice_date'],
        'status' => $inv['status'],
        'total_amount' => $inv['total_amount'],
        'seller_id' => $inv['seller_id'],
        'seller_name' => $inv['seller_name'],
        'seller_tax_number' => $inv['tax_number'],
        'seller_credentials_valid' => $credentialsOk,
        'problem' => !$credentialsOk ? '⚠️ هذه الفاتورة مرتبطة ببائع بيانات اعتماده غير صالحة!' : null
    ];
}

// 3. Summary
$validSellers = array_filter($result['diagnostic']['all_sellers'], fn($s) => $s['credentials_valid']);
$invalidSellers = array_filter($result['diagnostic']['all_sellers'], fn($s) => !$s['credentials_valid']);

$result['diagnostic']['summary'] = [
    'total_sellers' => count($sellers),
    'sellers_with_valid_credentials' => count($validSellers),
    'sellers_with_invalid_credentials' => count($invalidSellers),
    'total_invoices_checked' => count($invoices),
    'invoices_with_credential_problems' => count(array_filter($result['diagnostic']['recent_invoices'], fn($i) => !$i['seller_credentials_valid']))
];

// 4. Recommendations
$result['diagnostic']['recommendations'] = [];
foreach ($invalidSellers as $seller) {
    $result['diagnostic']['recommendations'][] = [
        'action' => 'تحديث بيانات الاعتماد',
        'seller_id' => $seller['id'],
        'seller_name' => $seller['seller_name'],
        'sql_template' => "UPDATE sellers SET client_id = 'YOUR_CLIENT_ID', secret_key = 'YOUR_SECRET_KEY', tax_number = 'YOUR_TAX', income_number = 'YOUR_INCOME' WHERE id = '{$seller['id']}';"
    ];
}

// 5. Full credentials for valid sellers (for reference)
$result['diagnostic']['valid_seller_full_credentials'] = [];
foreach ($sellers as $seller) {
    if ($seller['client_id_length'] > 30) {
        $result['diagnostic']['valid_seller_full_credentials'][] = [
            'seller_name' => $seller['seller_name'],
            'client_id' => $seller['client_id'],
            'secret_key' => $seller['secret_key'],
            'tax_number' => $seller['tax_number'],
            'income_number' => $seller['income_number']
        ];
    }
}

echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
