<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'php/db_connection.php';

/* ===== Login Check ===== */
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role     = $_SESSION['role'];
$isAdmin  = ($role === 'admin');

/* ===== Pagination ===== */
$limit  = 10;
$page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

/* ===== Delete Supplier ===== */
if ($isAdmin && isset($_GET['delete_id'])) {
    $stmt = $con->prepare("DELETE FROM suppliers WHERE id = ?");
    $stmt->bind_param("i", $_GET['delete_id']);
    $stmt->execute();
    header("Location: suppliers.php?page=$page");
    exit();
}

/* ===== Add / Update Supplier ===== */
if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = $_POST['name'];
    $mobile  = $_POST['mobile'];
    $email   = $_POST['email'];
    $address = $_POST['address'];

    if (!empty($_POST['id'])) {
        $stmt = $con->prepare(
            "UPDATE suppliers SET name=?, mobile=?, email=?, address=? WHERE id=?"
        );
        $stmt->bind_param("ssssi", $name, $mobile, $email, $address, $_POST['id']);
    } else {
        $stmt = $con->prepare(
            "INSERT INTO suppliers (name, mobile, email, address) VALUES (?,?,?,?)"
        );
        $stmt->bind_param("ssss", $name, $mobile, $email, $address);
    }

    $stmt->execute();
    header("Location: suppliers.php?page=$page");
    exit();
}

/* ===== Edit Data ===== */
$editData = null;
if ($isAdmin && isset($_GET['edit_id'])) {
    $stmt = $con->prepare("SELECT * FROM suppliers WHERE id=?");
    $stmt->bind_param("i", $_GET['edit_id']);
    $stmt->execute();
    $editData = $stmt->get_result()->fetch_assoc();
}

/* ===== Search ===== */
$search = $_GET['search'] ?? '';
$searchLike = "%$search%";

/* ===== Fetch Suppliers ===== */
$stmt = $con->prepare("
    SELECT * FROM suppliers
    WHERE name LIKE ? OR mobile LIKE ? OR email LIKE ?
    ORDER BY id DESC
    LIMIT ? OFFSET ?
");
$stmt->bind_param("sssii", $searchLike, $searchLike, $searchLike, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();

/* ===== Total Count ===== */
$stmt = $con->prepare("
    SELECT COUNT(*) FROM suppliers
    WHERE name LIKE ? OR mobile LIKE ? OR email LIKE ?
");
$stmt->bind_param("sss", $searchLike, $searchLike, $searchLike);
$stmt->execute();
$stmt->bind_result($total_suppliers);
$stmt->fetch();
$total_pages = ceil($total_suppliers / $limit);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Supplier Management</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
#form-section{display:none}
.pagination{justify-content:center}
</style>
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="container my-4">

<?php if ($isAdmin): ?>
<div class="text-end mb-3">
    <button class="btn btn-primary" onclick="showForm()">Add Supplier</button>
</div>
<?php endif; ?>

<!-- Form -->
<div id="form-section" class="card mb-4">
<div class="card-header bg-primary text-white d-flex justify-content-between">
<h4><?= $editData ? 'Edit Supplier' : 'Add Supplier' ?></h4>
<button class="btn-close" onclick="closeForm()"></button>
</div>
<div class="card-body">
<form method="post">
<input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
<input class="form-control mb-2" name="name" placeholder="Name" required value="<?= $editData['name'] ?? '' ?>">
<input class="form-control mb-2" name="mobile" placeholder="Mobile" required value="<?= $editData['mobile'] ?? '' ?>">
<input class="form-control mb-2" name="email" placeholder="Email"  value="<?= $editData['email'] ?? '' ?>">
<textarea class="form-control mb-2" name="address" placeholder="Address" required><?= $editData['address'] ?? '' ?></textarea>
<button class="btn btn-success">Save</button>
</form>
</div>
</div>

<!-- Search -->
<form class="mb-3">
<div class="input-group">
<input class="form-control" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search">
<button class="btn btn-primary">Search</button>
</div>
</form>

<!-- Table -->
<table class="table table-bordered table-hover">
<thead class="table-light">
<tr>
<th>#</th><th>Name</th><th>Phone</th><th>Email</th><th>Address</th><th>Date</th><th>Action</th>
</tr>
</thead>
<tbody>
<?php $i=$offset+1; while($row=$result->fetch_assoc()): ?>
<tr>
<td><?= $i++ ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['mobile'] ?></td>
<td><?= $row['email'] ?></td>
<td><?= $row['address'] ?></td>
<td><?= $row['created_at'] ?></td>
<td>
<?php if ($isAdmin): ?>
<a href="?edit_id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
<a href="?delete_id=<?= $row['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete?')">Delete</a>
<?php else: ?>
No Access
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

<!-- Pagination -->
<div class="pagination">
<?php if($page>1): ?>
<a href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>">Prev</a>
<?php endif; ?>
<span class="px-3">Page <?= $page ?> of <?= $total_pages ?></span>
<?php if($page<$total_pages): ?>
<a href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>">Next</a>
<?php endif; ?>
</div>

</div>

<script>
function showForm(){document.getElementById('form-section').style.display='block'}
function closeForm(){document.getElementById('form-section').style.display='none'}
<?php if($editData): ?>showForm();<?php endif; ?>
</script>

</body>
</html>
