<?php include("auth.php") ?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Partner Payment</title>
  <meta content="" name="description">
  <meta content="" name="keywords">
  <?php include("templates/inc.php"); ?>
  <script src="scripts/vendor.js" type="text/javascript" language="javascript"></script>
</head>

<body>

  <!-- ======= Header ======= -->
  <?php
  include("templates/header.php");
  ?>

  <!-- End Header -->

  <!-- ======= Sidebar ======= -->
  <?php
  include("templates/sidebar.php");

  ?>
  <!-- End Sidebar-->

  <main id="main" class="main">

    <div class="pagetitle">
      <h1>Payment</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
          <li class="breadcrumb-item">Payment</li>

        </ol>
      </nav>
      <hr>
      
    </div><!-- End Page Title -->

    <?php


require_once "./conn.php"; // ensure conn is available
$errors = [];
$success = "";

$designation_amounts = [
  'Silver'   => 1500,
  'Platinum' => 5000
];

// Handle POST actions: pay_all or pay_single
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';

  // Basic validation helper
  $validate_amount = function($amount) use (&$errors) {
    if ($amount === '' || !is_numeric($amount) || floatval($amount) <= 0) {
      $errors[] = "Enter a valid amount greater than 0.";
      return false;
    }
    return true;
  };

  if ($action === 'pay_all') {
    $designation = trim($_POST['designation'] ?? '');
    $amount = $designation_amounts[$designation] ?? 0;

    if ($designation === '') $errors[] = "Please select a designation.";
    if (!$validate_amount($amount)) { /* errors appended */ }

    if (empty($errors)) {
      $amount = floatval($amount);

      // Begin transaction
      mysqli_autocommit($conn, false);
      $ok = true;
      $paid_count = 0;

      $designation_safe = mysqli_real_escape_string($conn, $designation);
      $q = "SELECT id, v_code, name, IFNULL(wallet,0) as wallet FROM tbl_vendor 
            WHERE designation = '$designation_safe' AND status = 'Active' AND (deleted_at IS NULL OR deleted_at = '')";
      $res = mysqli_query($conn, $q);

      if ($res) {
        while ($vendor = mysqli_fetch_assoc($res)) {
          $tds=$amount*0.1;
          $netamt=$amount-$tds;
          $new_wallet = floatval($vendor['wallet']) + $netamt;
          $vid = intval($vendor['id']);

          // update wallet
          $q_up = "UPDATE tbl_vendor SET wallet = $new_wallet, updated_at = NOW() WHERE id = $vid";
          if (!mysqli_query($conn, $q_up)) {
            $ok = false;
            $errors[] = "Failed to update wallet for vendor ID {$vid}: " . mysqli_error($conn);
            break;
          }

          // insert into payment table
          $desc = "Transfer to Wallet " ;
          $q_ins = "INSERT INTO payment (vendor_id, payment_date, amount, tds, netamt, description, status) 
          VALUES ($vid, CURDATE(), $amount, $tds, $netamt, '" . mysqli_real_escape_string($conn, $desc) . "', 'paid')";

          if (!mysqli_query($conn, $q_ins)) {
            $ok = false;
            $errors[] = "Failed to insert payment record for vendor ID {$vid}: " . mysqli_error($conn);
            break;
          }

          $paid_count++;
        }
      } else {
        $ok = false;
        $errors[] = "Failed to fetch vendors: " . mysqli_error($conn);
      }

      if ($ok) {
        mysqli_commit($conn);
        $success = "Successfully paid ₹" . number_format($amount,2) . " to {$paid_count} vendor(s).";
      } else {
        mysqli_rollback($conn);
        if (empty($errors)) $errors[] = "Unknown error during payout. Transaction rolled back.";
      }
      mysqli_autocommit($conn, true);
    }
  }

  // Single vendor payment
//   if ($action === 'pay_single') {
//     $vendor_id = intval($_POST['vendor_id'] ?? 0);
//     $amount = trim($_POST['amount'] ?? '');

//     if ($vendor_id <= 0) $errors[] = "Invalid vendor selected.";
//     if (!$validate_amount($amount)) { /* errors appended */ }

//     if (empty($errors)) {
//       $amount = floatval($amount);
//       mysqli_autocommit($conn, false);
//       $ok = true;

//       // fetch vendor
//       $qv = "SELECT id, v_code, IFNULL(wallet,0) as wallet FROM tbl_vendor WHERE id = $vendor_id AND status='Active'";
//       $rv = mysqli_query($conn, $qv);
//       if ($rv && mysqli_num_rows($rv) === 1) {
//         $vendor = mysqli_fetch_assoc($rv);
//         $new_wallet = floatval($vendor['wallet']) + $amount;

//         $q_up = "UPDATE tbl_vendor SET wallet = $new_wallet, updated_at = NOW() WHERE id = $vendor_id";
//         if (!mysqli_query($conn, $q_up)) {
//           $ok = false;
//           $errors[] = "Failed to update wallet: " . mysqli_error($conn);
//         } else {
//           $desc = "Payout to vendor " . mysqli_real_escape_string($conn, $vendor['v_code']);
//           $q_ins = "INSERT INTO payment (payment_date, amount, description, status) 
//                     VALUES (CURDATE(), $amount, '" . mysqli_real_escape_string($conn, $desc) . "', 'completed')";
//           if (!mysqli_query($conn, $q_ins)) {
//             $ok = false;
//             $errors[] = "Failed to insert payment record: " . mysqli_error($conn);
//           }
//         }
//       } else {
//         $ok = false;
//         $errors[] = "Vendor not found or not active.";
//       }

//       if ($ok) {
//         mysqli_commit($conn);
//         $success = "Successfully paid ₹" . number_format($amount,2) . " to vendor ID {$vendor_id}.";
//       } else {
//         mysqli_rollback($conn);
//         if (empty($errors)) $errors[] = "Unknown error during payout. Transaction rolled back.";
//       }
//       mysqli_autocommit($conn, true);
//     }
//   }
 }

// Handle GET filter: which designation to show
$selected_designation = $_GET['designation'] ?? '';
$selected_designation = trim($selected_designation);


$fixed_amount = $designation_amounts[$selected_designation] ?? 0;

// Fetch vendor list if designation selected
$vendors = [];
if ($selected_designation !== '') {
  $designation_safe = mysqli_real_escape_string($conn, $selected_designation);
  $qv = "SELECT id, v_code, name, mobile, bank_name, acc_no, ifsc, acc_holder, IFNULL(wallet,0) as wallet 
         FROM tbl_vendor 
         WHERE designation = '$designation_safe' AND status='Active' AND (deleted_at IS NULL OR deleted_at = '') 
         ORDER BY name ASC";
  $rv = mysqli_query($conn, $qv);
  if ($rv) {
    while ($r = mysqli_fetch_assoc($rv)) $vendors[] = $r;
  } else {
    $errors[] = "Failed to fetch vendors: " . mysqli_error($conn);
  }
}
?>

<section class="section">
  <div class="row">
    <div class="col-lg-12">
      <div class="card" style="overflow:scroll;">
        <div class="card-body" id="payment-section">
          <h5 class="card-title">Partner Payment</h5>

          <!-- show success / error -->
          <?php if (!empty($success)): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
          <?php endif; ?>

          <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
              <ul class="mb-0">
                <?php foreach ($errors as $e) echo "<li>" . htmlspecialchars($e) . "</li>"; ?>
              </ul>
            </div>
          <?php endif; ?>

          <!-- Filter & Pay controls -->
<div class="row g-2 align-items-end" style="margin-bottom:12px;">
  <!-- GET filter form -->
  <form class="col-auto" method="get" id="filterForm">
  <div class="row g-2 align-items-end">
    <div class="col-auto">
      <label for="designation" class="form-label">Designation</label>
      <select class="form-select" id="designation" name="designation" required>
        <option value="" disabled selected hidden>Select Your Type</option>
        <option value="Silver" <?php if($selected_designation==='Silver') echo 'selected'; ?>>Silver</option>
        <option value="Platinum" <?php if($selected_designation==='Platinum') echo 'selected'; ?>>Platinum</option>
      </select>
    </div>

  </div>
</form>

  <!-- Pay All form (separate; NOT nested) -->
  <div class="col-auto">
  <form id="payAllForm" method="post" style="display:inline-block;">
    <input type="hidden" name="action" value="pay_all">
    <input type="hidden" name="designation" id="payall_designation" value="<?php echo htmlspecialchars($selected_designation); ?>">
    <input type="hidden" name="amount" id="payall_amount" value="<?php echo $fixed_amount; ?>">
    <button type="submit" class="btn btn-primary" id="payAllBtn" <?php if(empty($vendors)) echo 'disabled'; ?>>
      Pay All (₹<?php echo $fixed_amount; ?> each)
    </button>
  </form>
</div>


</div>            

          <!-- Vendor table -->
          <div class="table-responsive">
            <table id="vendorList" class="table table-striped dt-responsive nowrap" style="width:100%">
              <thead>
                <tr>
                  <th>SL NO</th>
                  <th>V_CODE</th>
                  <th>Name</th>
                  <th>Mobile</th>
                  <th>Bank</th>
                  <th>Acc Holder</th>
                  <th>Acc No</th>
                  <th>IFSC</th>
                  <th>Wallet (₹)</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($vendors)): ?>
                  <tr>
                    <td colspan="10" class="text-center">No vendors to show. </td>
                  </tr>
                <?php else: ?>
                  <?php $sl = 1; foreach ($vendors as $v): ?>
                    <tr>
                      <td><?php echo $sl++; ?></td>
                      <td><?php echo htmlspecialchars($v['v_code']); ?></td>
                      <td><?php echo htmlspecialchars($v['name']); ?></td>
                      <td><?php echo htmlspecialchars($v['mobile']); ?></td>
                      <td><?php echo htmlspecialchars($v['bank_name']); ?></td>
                      <td><?php echo htmlspecialchars($v['acc_holder']); ?></td>
                      <td><?php echo htmlspecialchars($v['acc_no']); ?></td>
                      <td><?php echo htmlspecialchars($v['ifsc']); ?></td>
                      <td><?php echo number_format(floatval($v['wallet']),2); ?></td>
                      <!--<td>-->
                        <!-- Pay single vendor -->
                      <!--  <form method="post" style="display:inline-block;">-->
                      <!--    <input type="hidden" name="action" value="pay_single">-->
                      <!--    <input type="hidden" name="vendor_id" value="<?php echo intval($v['id']); ?>">-->
                      <!--    <input type="hidden" name="amount" value="<?php echo $fixed_amount; ?>">-->
                      <!--    <button type="submit" class="btn btn-sm btn-success" <?php if($fixed_amount<=0) echo 'disabled'; ?>>-->
                      <!--      Pay (₹<?php echo $fixed_amount; ?>)-->
                      <!--    </button>-->
                      <!--  </form>-->
                      <!--</td>-->
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

        </div>
      </div>
    </div>
  </div>
</section>


  </main><!-- End #main -->
  
  <script>
// Auto-submit when dropdown changes
document.getElementById("designation").addEventListener("change", function() {
  document.getElementById("filterForm").submit();
});
</script>

  <!-- ======= Footer ======= -->
  <?php
  include("templates/footer.php");
  ?>
  <!-- End Footer -->


  <?php include("templates/vendors.php"); ?>

</body>

</html>