<?php
session_start();

// كلمة السر الخاصة بالدخول
$password = "522522";

// إذا المستخدم طلب تسجيل خروج
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// إذا لم يتم تسجيل الدخول
if (!isset($_SESSION['logged_in'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === $password) {
            $_SESSION['logged_in'] = true;
            header("Location: index.php");
            exit;
        } else {
            $error = "❌ كلمة المرور غير صحيحة";
        }
    }

    // نموذج تسجيل الدخول
    echo '<!DOCTYPE html>
    <html lang="ar">
    <head>
    <meta name="robots" content="noindex, nofollow">

        <meta charset="UTF-8">
        <title>تسجيل الدخول</title>
        <style>
            body {font-family: Arial; display:flex; justify-content:center; align-items:center; height:100vh; background:#f2f2f2;}
            form {background:#fff; padding:20px; border-radius:10px; box-shadow:0 0 10px rgba(0,0,0,0.2);}
            input {padding:10px; margin:10px 0; width:100%;}
            button {padding:10px; width:100%; background:#333; color:#fff; border:none; cursor:pointer;}
            .error {color:red;}
        </style>
    </head>
    <body>
        <form method="post">
            <h2>🔒 تسجيل الدخول</h2>';
    if (!empty($error)) echo "<p class='error'>$error</p>";
    echo '  <input type="password" name="password" placeholder="أدخل كلمة السر" required>
            <button type="submit">دخول</button>
        </form>
    </body>
    </html>';
    exit;
}
?>


<?php
session_start();

// كلمة السر الخاصة بالدخول
$password = "12345";

// إذا المستخدم طلب تسجيل خروج
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// إذا لم يتم تسجيل الدخول
if (!isset($_SESSION['logged_in'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === $password) {
            $_SESSION['logged_in'] = true;
            header("Location: index.php");
            exit;
        } else {
            $error = "❌ كلمة المرور غير صحيحة";
        }
    }

    // نموذج تسجيل الدخول
    echo '<!DOCTYPE html>
    <html lang="ar">
    <head>
        <meta charset="UTF-8">
        <title>تسجيل الدخول</title>
        <style>
            body {font-family: Arial; display:flex; justify-content:center; align-items:center; height:100vh; background:#f2f2f2;}
            form {background:#fff; padding:20px; border-radius:10px; box-shadow:0 0 10px rgba(0,0,0,0.2);}
            input {padding:10px; margin:10px 0; width:100%;}
            button {padding:10px; width:100%; background:#333; color:#fff; border:none; cursor:pointer;}
            .error {color:red;}
        </style>
    </head>
    <body>
        <form method="post">
            <h2>🔒 تسجيل الدخول</h2>';
    if (!empty($error)) echo "<p class='error'>$error</p>";
    echo '  <input type="password" name="password" placeholder="أدخل كلمة السر" required>
            <button type="submit">دخول</button>
        </form>
    </body>
    </html>';
    exit;
}
?>


<?php
session_start();

// تحقق من تسجيل الدخول
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require 'config.php';
require __DIR__ . '/vendor/autoload.php';
use Mpdf\Mpdf;

// جلب العملاء والمواد
$customers = $conn->query("SELECT * FROM customers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$products = $conn->query("SELECT * FROM products ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

$quick_message = "";
$manual_message = "";

// =====================
// معالجة الوصل السريع
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quick_text'])) {
    $text = $_POST['quick_text'];

    preg_match('/([\d.,]+)\s*(كغ|كجم|قطعة)?/u', $text, $qty_match);
    preg_match('/سعر\s*([\d.,]+)/u', $text, $price_match);

    $quantity = isset($qty_match[1]) ? floatval(str_replace(',', '.', $qty_match[1])) : 1;
    $unit = $qty_match[2] ?? '';
    $price = isset($price_match[1]) ? floatval(str_replace(',', '.', $price_match[1])) : 0;

    $remaining = preg_replace('/([\d.,]+\s*(كغ|كجم|قطعة)?|سعر\s*[\d.,]+)/u', '', $text);
    $remaining = trim($remaining);

    // البحث عن العميل
    $stmt = $conn->prepare("SELECT * FROM customers WHERE name LIKE ?");
    $stmt->execute(['%' . $remaining . '%']);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$customer) $quick_message = "❌ لم يتم العثور على العميل.";
    else {
        $product_name = trim(str_replace($customer['name'], '', $remaining));

        // البحث عن المادة أو إضافتها إذا لم توجد
        $stmt = $conn->prepare("SELECT * FROM products WHERE name LIKE ?");
        $stmt->execute(['%' . $product_name . '%']);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$product) {
            $stmt = $conn->prepare("INSERT INTO products (name, price, unit) VALUES (?, 0, ?)");
            $stmt->execute([$product_name, $unit]);
            $product_id = $conn->lastInsertId();
        } else $product_id = $product['id'];

        // إنشاء الوصل
        $stmt = $conn->prepare("INSERT INTO deliveries (customer_id, total) VALUES (?, ?)");
        $stmt->execute([$customer['id'], $price * $quantity]);
        $delivery_id = $conn->lastInsertId();

        $stmt = $conn->prepare("INSERT INTO delivery_items (delivery_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
        $stmt->execute([$delivery_id, $product_id, $quantity, $price]);

        // توليد PDF
        $mpdf = new Mpdf(['format'=>'A5-L']);
        $html = "
        <h2>وصل تسليم رقم #$delivery_id</h2>
        <p>العميل: {$customer['name']}</p>
        <table border='1' style='width:100%;border-collapse:collapse;'>
            <tr><th>المادة</th><th>الكمية</th><th>السعر</th><th>المجموع</th></tr>
            <tr>
                <td>$product_name</td>
                <td>$quantity $unit</td>
                <td>$price</td>
                <td>".($quantity*$price)."</td>
            </tr>
        </table>
        <h3>الإجمالي: ".($quantity*$price)." $</h3>
        <p>التوقيع: ________________</p>
        ";
        $filename = "delivery_quick_{$delivery_id}.pdf";
        $pdf_path = $PDF_DIR . "/" . $filename;
        $mpdf->WriteHTML($html);
        $mpdf->Output($pdf_path,'F');
        $mpdf->Output($filename,'I');
        exit;
    }
}

// =====================
// معالجة الوصل اليدوي
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_customer'])) {
    $customer_id = $_POST['manual_customer'];
    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $prices = $_POST['price'] ?? [];

    if (!$customer_id || empty($product_ids)) $manual_message = "❌ اختر العميل وأضف المنتجات.";
    else {
        $total = 0;
        foreach ($product_ids as $k => $pid) {
            $total += $quantities[$k]*$prices[$k];
        }

        $stmt = $conn->prepare("INSERT INTO deliveries (customer_id, total) VALUES (?, ?)");
        $stmt->execute([$customer_id, $total]);
        $delivery_id = $conn->lastInsertId();

        foreach ($product_ids as $k => $pid) {
            $stmt = $conn->prepare("INSERT INTO delivery_items (delivery_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
            $stmt->execute([$delivery_id, $pid, $quantities[$k], $prices[$k]]);
        }

        $stmt = $conn->prepare("SELECT * FROM customers WHERE id=?");
        $stmt->execute([$customer_id]);
        $customer = $stmt->fetch(PDO::FETCH_ASSOC);

        $mpdf = new Mpdf(['format'=>'A5-L']);
        $html = "<h2>وصل تسليم رقم #$delivery_id</h2><p>العميل: {$customer['name']}</p>";
        $html .= "<table border='1' style='width:100%;border-collapse:collapse;'>
            <tr><th>المادة</th><th>الكمية</th><th>السعر</th><th>المجموع</th></tr>";

        foreach ($product_ids as $k => $pid) {
            $stmt = $conn->prepare("SELECT name FROM products WHERE id=?");
            $stmt->execute([$pid]);
            $p = $stmt->fetch(PDO::FETCH_ASSOC);
            $html .= "<tr>
                <td>{$p['name']}</td>
                <td>{$quantities[$k]}</td>
                <td>{$prices[$k]}</td>
                <td>".($quantities[$k]*$prices[$k])."</td>
            </tr>";
        }

        $html .= "</table><h3>الإجمالي: $total $</h3><p>التوقيع: ________________</p>";
        $filename = "delivery_manual_{$delivery_id}.pdf";
        $pdf_path = $PDF_DIR . "/" . $filename;
        $mpdf->WriteHTML($html);
        $mpdf->Output($pdf_path,'F');
        $mpdf->Output($filename,'I');
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>لوحة تحكم Alj</title>
<meta name="robots" content="noindex, nofollow"> <!-- منع الفهرسة -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body{background:#f5f5f5;}
.card{margin-bottom:20px;}
.list-group-item:hover{cursor:pointer;}
</style>
<script>
function addRow() {
    const table = document.getElementById("manual_items");
    const row = table.insertRow();
    row.innerHTML = `<td>
        <select name="product_id[]" required class="form-select">
            <option value="">اختر مادة</option>
            <?php foreach ($products as $p): ?>
                <option value="<?= htmlspecialchars($p['id']) ?>"><?= htmlspecialchars($p['name']) ?></option>
            <?php endforeach; ?>
        </select></td>
        <td><input type="number" name="quantity[]" class="form-control" step="0.01" required></td>
        <td><input type="number" name="price[]" class="form-control" step="0.01" required placeholder="السعر الخاص بالعميل"></td>
        <td><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove()">✖</button></td>`;
}

// =====================
// البحث الذكي للعميل الوصل اليدوي
// =====================
$(document).ready(function(){
    $("#manual_customer_search").on("input", function(){
        var query = $(this).val();
        if(query.length >= 2){
            $.ajax({
                url: 'search_customer.php',
                method: 'GET',
                data: {q: query},
                success: function(data){
                    $("#manual_customer_list").html(data);
                }
            });
        } else { $("#manual_customer_list").html(''); }
    });

    $(document).on('click', '.customer-item', function(){
        var name = $(this).text();
        var id = $(this).data('id');
        $("#manual_customer_search").val(name);
        $("#manual_customer_id").val(id);
        $("#manual_customer_list").html('');
    });
});
</script>
</head>
<body class="container mt-4">
<h1 class="mb-4">لوحة تحكم Alj</h1>

<!-- زر تسجيل الخروج -->
<div class="mb-3">
    <a href="logout.php" class="btn btn-danger">🚪 تسجيل الخروج</a>
</div>

<!-- إدارة البيانات -->
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card shadow">
            <div class="card-header bg-info text-white">🛠 إدارة البيانات</div>
            <div class="card-body">
                <a href="new_customer.php" class="btn btn-success mb-2">➕ إضافة عميل</a>
                <a href="new_product.php" class="btn btn-success mb-2">➕ إضافة مادة</a>
                <a href="upload_customers.php" class="btn btn-info mb-2">⬆️ رفع عملاء من Excel</a>
                <a href="upload_products.php" class="btn btn-info mb-2">⬆️ رفع مواد من Excel</a>
            </div>
        </div>
    </div>
</div>

<div class="row">
<!-- الوصل اليدوي -->
<div class="col-md-6">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">📝 إنشاء وصل يدوي</div>
        <div class="card-body">
            <?php if($manual_message) echo "<div class='alert alert-danger'>$manual_message</div>"; ?>
            <form method="post">
                <div class="mb-3 position-relative">
                    <label>اختر العميل:</label>
                    <input type="text" id="manual_customer_search" class="form-control" placeholder="اكتب اسم العميل" required>
                    <div id="manual_customer_list" class="list-group mt-1"></div>
                    <input type="hidden" name="manual_customer" id="manual_customer_id" required>
                </div>
                <table class="table table-bordered" id="manual_items">
                    <tr><th>المادة</th><th>الكمية</th><th>السعر</th><th>حذف</th></tr>
                </table>
                <button type="button" class="btn btn-secondary mb-2" onclick="addRow()">➕ إضافة مادة</button>
                <button type="submit" class="btn btn-success w-100">💾 إنشاء PDFيمكن معاينة PDF أو إرساله للطابعة مباشرة عبر Epson Cloud.
            </form>
        </div>
    </div>
</div>

<!-- الوصل السريع -->
<div class="col-md-6">
    <div class="card shadow">
        <div class="card-header bg-warning text-dark">⚡ إنشاء وصل سريع</div>
        <div class="card-body">
            <?php if($quick_message) echo "<div class='alert alert-danger'>$quick_message</div>"; ?>
            <form method="post">
                <div class="mb-3">
                    <textarea name="quick_text" class="form-control" rows="3" placeholder="مثال: 600 كغ جوز هند كامل اندونيسي سعر 4.400$ شركة الشرباتي" required></textarea>
                </div>
                <button class="btn btn-success w-100">💾 إنشاء PDF وصل سريع</button>
            </form>
        </div>
    </div>
</div>

</div>
</body>
</html>
