<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include 'config.php';

// 1. التأكد من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$current_page = basename($_SERVER['PHP_SELF']); 

// 2. فحص الصلاحية
$stmt_perm = $pdo->prepare("
    SELECT up.id 
    FROM user_permissions up
    JOIN pages p ON up.page_id = p.id
    WHERE up.user_id = ? AND p.page_url = ?
");
$stmt_perm->execute([$user_id, $current_page]);
$has_permission = $stmt_perm->fetch();

if (!$has_permission) {
    die("<div style='text-align:center; margin-top:50px; font-family:sans-serif; direction:rtl;'>
            <h2 style='color:#dc3545;'>عفواً! لا تمتلك صلاحية للوصول إلى هذه الصفحة.</h2>
            <a href='dashboard.php'>العودة للرئيسية</a>
         </div>");
}

// 3. معالجة إضافة مورد جديد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_supplier') {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $company_name = trim($_POST['company_name'] ?? '');

    if (!empty($name)) {
        try {
            $stmt_insert = $pdo->prepare("INSERT INTO suppliers (name, phone, company_name, balance) VALUES (?, ?, ?, 0)");
            $stmt_insert->execute([$name, $phone, $company_name]);
            header("Location: suppliers_manager.php");
            exit;
        } catch (PDOException $e) {
            echo "<script>alert('حدث خطأ أثناء الحفظ: " . $e->getMessage() . "');</script>";
        }
    }
}

// 4. جلب البيانات
$suppliers_list = [];
$selected_supplier = [];
$supplier_invoices = [];

if (!isset($_GET['profile_id'])) {
    $stmt_suppliers = $pdo->prepare("SELECT * FROM suppliers ORDER BY id DESC");
    $stmt_suppliers->execute();
    $suppliers_list = $stmt_suppliers->fetchAll(PDO::FETCH_ASSOC);
} else {
    $profile_id = intval($_GET['profile_id']);
    
    $stmt_supplier = $pdo->prepare("SELECT * FROM suppliers WHERE id = ?");
    $stmt_supplier->execute([$profile_id]);
    $selected_supplier = $stmt_supplier->fetch(PDO::FETCH_ASSOC);

    // [التعديل هنا]: تم تغيير purchases إلى purchase_invoices لتطابق اسم جدولك الحقيقي
    $stmt_invoices = $pdo->prepare("SELECT * FROM purchase_invoices WHERE supplier_id = ? ORDER BY id DESC");
    $stmt_invoices->execute([$profile_id]);
    $supplier_invoices = $stmt_invoices->fetchAll(PDO::FETCH_ASSOC);
}
?>

<style>
    :root { --o-purple: #714B67; --o-teal: #008784; --o-bg: #f9f9f9; }
    body { background: var(--o-bg); font-family: 'Segoe UI', Tahoma, sans-serif; direction: rtl; margin: 0; }
    .o_control_panel { background: #fff; border-bottom: 1px solid #d9d9d9; padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; }
    .o_content { padding: 20px; max-width: 1200px; margin: 0 auto; }
    .o_form_sheet { background: white; border: 1px solid #c8c8c8; border-radius: 2px; padding: 25px; }
    .o_notebook_headers { display: flex; border-bottom: 1px solid #dee2e6; margin-bottom: 15px; list-style: none; padding: 0; }
    .o_notebook_headers a { padding: 10px 20px; text-decoration: none; color: #4c4c4c; font-weight: bold; }
    .o_notebook_headers a.active { border-bottom: 3px solid var(--o-purple); color: var(--o-purple); }
    .o_input { padding: 6px 10px; border: 1px solid #ccc; border-radius: 4px; width: 100%; }
    .btn-o { background: var(--o-purple); color: white; border: none; padding: 7px 15px; border-radius: 4px; cursor: pointer; }
    .o_list_view { width: 100%; border-collapse: collapse; margin-top: 10px; }
    .o_list_view th { background: #f3f3f3; padding: 10px; border-bottom: 2px solid #d9d9d9; }
    .o_list_view td { padding: 10px; border-bottom: 1px solid #e6e6e6; }
</style>

<div class="o_content">
    <div class="o_form_sheet">
        <ul class="o_notebook_headers">
            <li><a href="suppliers_manager.php" class="<?= !isset($_GET['profile_id']) ? 'active' : '' ?>">قائمة الموردين</a></li>
            <?php if(!empty($selected_supplier)): ?>
                <li><a href="#" class="active">بروفايل: <?= htmlspecialchars($selected_supplier['name']) ?></a></li>
            <?php endif; ?>
        </ul>

        <?php if(!isset($_GET['profile_id'])): ?>
            <form method="POST" action="" class="mb-4" style="background: #fafafa; padding: 20px; border: 1px solid #eee;">
                <input type="hidden" name="action" value="add_supplier">
                <h5>تسجيل مورد جديد</h5>
                <div style="display: flex; gap: 15px;">
                    <input type="text" name="name" class="o_input" placeholder="اسم المورد" required>
                    <input type="text" name="phone" class="o_input" placeholder="رقم الهاتف">
                    <input type="text" name="company_name" class="o_input" placeholder="اسم الشركة">
                    <button type="submit" class="btn-o">حفظ</button>
                </div>
            </form>

            <table class="o_list_view">
                <thead><tr><th>اسم المورد</th><th>الشركة</th><th>الهاتف</th><th>الرصيد</th><th>العمليات</th></tr></thead>
                <tbody>
                    <?php foreach($suppliers_list as $sup): ?>
                    <tr>
                        <td><?= htmlspecialchars($sup['name']) ?></td>
                        <td><?= htmlspecialchars($sup['company_name'] ?? '---') ?></td>
                        <td><?= htmlspecialchars($sup['phone'] ?? '---') ?></td>
                        <td style="color:red; font-weight:bold;"><?= number_format($sup['balance'], 2) ?></td>
                        <td><a href="?profile_id=<?= $sup['id'] ?>" class="btn-o" style="background:var(--o-teal);">كشف الفواتير</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <h4>سجل الفواتير لـ <?= htmlspecialchars($selected_supplier['name']) ?></h4>
            <table class="o_list_view">
                <thead><tr><th>رقم الفاتورة</th><th>التاريخ</th><th>الإجمالي</th><th>المدفوع</th><th>المتبقي</th></tr></thead>
                <tbody>
                    <?php foreach($supplier_invoices as $inv): 
                        $rest = $inv['total_amount'] - $inv['paid_amount'];
                    ?>
                    <tr>
                        <td>#<?= $inv['id'] ?></td>
                        <td><?= $inv['invoice_date'] ?></td>
                        <td><?= number_format($inv['total_amount'], 2) ?></td>
                        <td><?= number_format($inv['paid_amount'], 2) ?></td>
                        <td style="color:red; font-weight:bold;"><?= number_format($rest, 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>