<?php
include 'auth_check.php';
requireAdminAccess('sale.php');

$message = '';
$messageClass = 'success-box';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $company_name = trim($_POST['company_name'] ?? '');
    $agent_name = trim($_POST['agent_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $id = (int)($_POST['supplier_id'] ?? 0);
    $date = date('Y-m-d');
    $time = date('H:i:s');
    $user = $_SESSION['name'];

    if ($action === 'add_supplier') {
        if ($company_name === '' || $agent_name === '') {
            $message = 'Please fill required supplier fields.';
            $messageClass = 'error-box';
        } else {
            $stmt = $conn->prepare("INSERT INTO suppliers (company_name, agent_name, email, mobile, entered_date, entered_time, entered_user) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssss", $company_name, $agent_name, $email, $mobile, $date, $time, $user);
            $stmt->execute();
            $message = 'Supplier saved successfully.';
        }
    }

    if ($action === 'edit_supplier') {
        if ($id > 0 && $company_name !== '' && $agent_name !== '') {
            $stmt = $conn->prepare("UPDATE suppliers SET company_name=?, agent_name=?, email=?, mobile=? WHERE id=?");
            $stmt->bind_param("ssssi", $company_name, $agent_name, $email, $mobile, $id);
            $stmt->execute();
            $message = 'Supplier updated successfully.';
        } else {
            $message = 'Please select a supplier and fill required fields.';
            $messageClass = 'error-box';
        }
    }

    if ($action === 'delete_supplier') {
        if ($id > 0) {
            $stmt = $conn->prepare("DELETE FROM suppliers WHERE id=?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $message = 'Supplier deleted successfully.';
        } else {
            $message = 'Please select a supplier.';
            $messageClass = 'error-box';
        }
    }
}

$search = trim($_GET['search_company'] ?? '');
if ($search !== '') {
    $stmt = $conn->prepare("SELECT * FROM suppliers WHERE company_name LIKE CONCAT('%', ?, '%') ORDER BY company_name ASC");
    $stmt->bind_param("s", $search);
    $stmt->execute();
    $suppliers = $stmt->get_result();
} else {
    $suppliers = $conn->query("SELECT * FROM suppliers ORDER BY company_name ASC");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Suppliers</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('suppliers'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <?php if ($message !== '') { ?>
            <div class="message-box <?php echo $messageClass; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php } ?>

        <div class="form-card">
            <h2>Suppliers</h2>
            <form method="POST" id="supplierForm">
                <input type="hidden" name="supplier_id" id="supplier_id">
                <input type="text" name="company_name" id="company_name" placeholder="Company Name" onkeyup="filterSupplierTable()" required>
                <input type="text" name="agent_name" id="agent_name" placeholder="Agent Name" required>
                <input type="email" name="email" id="email" placeholder="Email">
                <input type="text" name="mobile" id="mobile" placeholder="Mobile">
                <button type="submit" name="action" value="add_supplier">Add</button>
                <button type="submit" name="action" value="edit_supplier">Edit</button>
                <button type="submit" name="action" value="delete_supplier" onclick="return confirm('Delete this supplier?')">Delete</button>
            </form>
        </div>

        <div class="table-card">
            <form method="GET" class="search-bar">
                <input type="text" name="search_company" id="supplier_search_company" placeholder="Search Company Name" value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit">Search</button>
            </form>

            <div class="table-scroll">
                <table id="supplierTable">
                    <tr>
                        <th>ID</th>
                        <th>Company Name</th>
                        <th>Agent Name</th>
                        <th>Email</th>
                        <th>Mobile</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>User</th>
                    </tr>
                    <?php while ($row = $suppliers->fetch_assoc()) { ?>
                    <tr onclick="fillSupplierForm('<?php echo $row['id']; ?>','<?php echo htmlspecialchars($row['company_name'], ENT_QUOTES); ?>','<?php echo htmlspecialchars($row['agent_name'], ENT_QUOTES); ?>','<?php echo htmlspecialchars($row['email'], ENT_QUOTES); ?>','<?php echo htmlspecialchars($row['mobile'], ENT_QUOTES); ?>')">
                        <td><?php echo $row['id']; ?></td>
                        <td><?php echo htmlspecialchars($row['company_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['agent_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['email']); ?></td>
                        <td><?php echo htmlspecialchars($row['mobile']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_date']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_time']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_user']); ?></td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>
    </main>
</div>

<script>
function fillSupplierForm(id, company, agent, email, mobile) {
    document.getElementById('supplier_id').value = id;
    document.getElementById('company_name').value = company;
    document.getElementById('agent_name').value = agent;
    document.getElementById('email').value = email;
    document.getElementById('mobile').value = mobile;
}

function filterSupplierTable() {
    const input = document.getElementById('company_name').value.toLowerCase();
    const rows = document.querySelectorAll('#supplierTable tr');
    rows.forEach((row, index) => {
        if (index === 0) return;
        const company = row.children[1].innerText.toLowerCase();
        row.style.display = company.includes(input) ? '' : 'none';
    });
}
</script>
</body>
</html>