<?php
session_start();
include 'php/db_connection.php';

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

// Process Payment
if(isset($_POST['pay_supplier'])){
    $supplier_id = $_POST['supplier_id'];
    $pay_amount = floatval($_POST['pay_amount']);

    // Get total bill from product_cat & product
    $row = $con->query("
        SELECT COALESCE(SUM(p.Quantity * pc.purchase_price),0) AS total_bill
        FROM product_cat pc
        LEFT JOIN product p ON p.Product_id = pc.Product_id
        WHERE pc.supplier_id='$supplier_id'
    ")->fetch_assoc();

    $total_bill = $row['total_bill'];

    // Get previous paid_amount
    $bill_row = $con->query("SELECT paid_amount FROM supplier_bills WHERE supplier_id='$supplier_id'")->fetch_assoc();
    $paid_amount = $bill_row['paid_amount'] ?? 0;

    $new_paid = $paid_amount + $pay_amount;
    $due_amount = max($total_bill - $new_paid, 0);

    // Update or insert supplier_bills
    $check = $con->query("SELECT * FROM supplier_bills WHERE supplier_id='$supplier_id'");
    if($check->num_rows > 0){
        $con->query("UPDATE supplier_bills SET paid_amount=$new_paid, due_amount=$due_amount, total_bill=$total_bill WHERE supplier_id='$supplier_id'");
    } else {
        $con->query("INSERT INTO supplier_bills (supplier_id, total_bill, paid_amount, due_amount) VALUES ('$supplier_id', '$total_bill', '$pay_amount', '$due_amount')");
    }

    header("Location: suppliers_bill.php");
    exit();
}

// Pagination & search
$limit = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$start = ($page - 1) * $limit;
$search = isset($_GET['search']) ? $_GET['search'] : '';

$query = "
SELECT s.id, s.name, s.mobile, s.email,
       COALESCE(SUM(p.Quantity * pc.purchase_price),0) AS total_bill,
       COALESCE(sb.paid_amount,0) AS paid_amount,
       (COALESCE(SUM(p.Quantity * pc.purchase_price),0) - COALESCE(sb.paid_amount,0)) AS due_amount
FROM suppliers s
LEFT JOIN product_cat pc ON pc.supplier_id = s.id
LEFT JOIN product p ON p.Product_id = pc.Product_id
LEFT JOIN supplier_bills sb ON sb.supplier_id = s.id
WHERE s.name LIKE ?
GROUP BY s.id
ORDER BY s.name ASC
LIMIT ?, ?
";

$stmt = $con->prepare($query);
$search_param = "%$search%";
$stmt->bind_param("sii", $search_param, $start, $limit);
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Supplier Bills</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <?php include 'sidebar.php'; ?>
</head>
<body>
<div class="container mt-4">
    <h2>Supplier Bills</h2>

    <form method="get" class="form-inline mb-3">
        <input type="text" name="search" class="form-control mr-2" placeholder="Search Supplier" value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn btn-primary">Search</button>
    </form>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Supplier Name</th>
                <th>Mobile</th>
                <th>Email</th>
                <th>Total Bill</th>
                <th>Paid Amount</th>
                <th>Due Amount</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $result->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['name']) ?></td>
                <td><?= htmlspecialchars($row['mobile']) ?></td>
                <td><?= htmlspecialchars($row['email']) ?></td>
                <td><?= number_format($row['total_bill'],2) ?></td>
                <td><?= number_format($row['paid_amount'],2) ?></td>
                <td><?= number_format($row['due_amount'],2) ?></td>
                <td>
                    <button class="btn btn-success btn-sm pay-btn" data-id="<?= $row['id'] ?>" data-name="<?= htmlspecialchars($row['name']) ?>" data-due="<?= $row['due_amount'] ?>" data-toggle="modal" data-target="#payModal">Pay</button>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <?php
    $count_stmt = $con->prepare("SELECT COUNT(*) as total FROM suppliers WHERE name LIKE ?");
    $count_stmt->bind_param("s", $search_param);
    $count_stmt->execute();
    $total_count = $count_stmt->get_result()->fetch_assoc()['total'];
    $total_pages = ceil($total_count / $limit);
    ?>

    <nav>
        <ul class="pagination">
            <?php for($i=1; $i<=$total_pages; $i++): ?>
                <li class="page-item <?= ($i==$page)?'active':'' ?>">
                    <a class="page-link" href="?page=<?= $i ?>&search=<?= htmlspecialchars($search) ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
</div>

<!-- Pay Modal -->
<div class="modal fade" id="payModal" tabindex="-1" role="dialog" aria-labelledby="payModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form method="post">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="payModalLabel">Pay Supplier</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
          <input type="hidden" name="supplier_id" id="modal_supplier_id">
          <div class="form-group">
              <label>Supplier:</label>
              <input type="text" id="modal_supplier_name" class="form-control" readonly>
          </div>
          <div class="form-group">
              <label>Due Amount:</label>
              <input type="text" id="modal_due" class="form-control" readonly>
          </div>
          <div class="form-group">
              <label>Payment Amount:</label>
              <input type="number" name="pay_amount" class="form-control" step="0.01" max="0" id="modal_pay_amount" required>
          </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="pay_supplier" class="btn btn-primary">Submit Payment</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
    </form>
  </div>
</div>

<script>
$(document).ready(function(){
    $('.pay-btn').click(function(){
        var supplier_id = $(this).data('id');
        var supplier_name = $(this).data('name');
        var due = $(this).data('due');
        $('#modal_supplier_id').val(supplier_id);
        $('#modal_supplier_name').val(supplier_name);
        $('#modal_due').val(due);
        $('#modal_pay_amount').attr('max', due);
    });
});
</script>

</body>
</html>
