<?php
  session_start();
  // 1. Security Check
  if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
  }
  require_once 'system/conn.php';

  $message = "";

  // ---------------------------------------------------
  //  HANDLE FORM SUBMISSION
  // ---------------------------------------------------
  if(isset($_POST["submit"]))
  {
      // 1. Capture Form Inputs
      $selected_category = $_POST['payment_category']; // "Regular Bank Sheet", etc.
      $payment_type      = $_POST['payment_type'];     // "Bank Transfer", "Cheque", etc.
      $payment_ref_id    = trim($_POST['payment_id']); // UTR or Cheque No
      $narration         = trim($_POST['narration']);
      $payment_date      = $_POST['payment_date'];
      $branch            = $_SESSION['branch'];
      $updated_date      = date("Y-m-d");

      // 2. Calculate Salary Month (Previous Month Logic)
      // If Payment Date is Feb 2026, we are paying Jan 2026 Salary
      $timestamp = strtotime("-1 month", strtotime($payment_date));
      $salary_month = date("m", $timestamp);
      $salary_year  = date("Y", $timestamp);

      try {
          // 3. Start Transaction (Ensures data integrity)
          $conn->beginTransaction();

          // 4. Determine which Employees to Pay
          // We assume "Payment For" in DB stores Employee ID, so we select the IDs here.
          $eligible_employees = [];
          
          // Base Query: Select Unpaid Employees for this Month/Year/Branch
          $base_sql = "SELECT emp_id FROM emp_salary 
                       WHERE month = :m AND year = :y AND branch = :b 
                       AND payment_status != '1'"; // Only select UNPAID

          if ($selected_category == "Regular Bank Sheet") {
              // Logic: No Block, No Cheque, Has Account Number
              $sql = $base_sql . " AND (block IS NULL OR block = '') 
                                   AND (cheque IS NULL OR cheque = '') 
                                   AND (ac_no IS NOT NULL AND ac_no != '')";
          } 
          elseif ($selected_category == "Regular Cheque Sheet") {
              // Logic: Marked as Cheque OR Missing Account Number
              $sql = $base_sql . " AND ((cheque = 'yes') OR (ac_no IS NULL OR ac_no = ''))";
          }
          elseif ($selected_category == "OT Bank Sheet") {
              // Logic: Same account rules, applied to OT context if needed
              $sql = $base_sql . " AND (block IS NULL OR block = '') 
                                   AND (cheque IS NULL OR cheque = '') 
                                   AND (ac_no IS NOT NULL AND ac_no != '')";
          }
          elseif ($selected_category == "OT Cheque Sheet") {
               $sql = $base_sql . " AND ((cheque = 'yes') OR (ac_no IS NULL OR ac_no = ''))";
          }
          else {
              throw new Exception("Invalid Payment Category Selected");
          }

          // Execute Selection
          $stmt = $conn->prepare($sql);
          $stmt->execute([':m' => $salary_month, ':y' => $salary_year, ':b' => $branch]);
          $eligible_employees = $stmt->fetchAll(PDO::FETCH_ASSOC);

          $count = 0;

          // 5. Prepare Insert/Update Statements
          $update_salary_stmt = $conn->prepare("UPDATE emp_salary SET payment_status = '1' 
                                                WHERE emp_id = :eid AND month = :m AND year = :y AND branch = :b");
          
          $insert_payment_stmt = $conn->prepare("INSERT INTO payment_tbl 
              (payment_for, payment_type, payment_id, narration, branch, payment_date, month, year, updated_date) 
              VALUES (:emp_id, :ptype, :pid, :narr, :branch, :pdate, :m, :y, :update_d)");

          // 6. Loop through Employees and Record Payment
          foreach ($eligible_employees as $emp) {
              $eid = $emp['emp_id'];

              // A. Mark Salary as Paid
              $update_salary_stmt->execute([
                  ':eid' => $eid, 
                  ':m' => $salary_month, 
                  ':y' => $salary_year, 
                  ':b' => $branch
              ]);

              // B. Record the Payment
              // NOTE: We map 'emp_id' to the 'payment_for' column in database
              $insert_payment_stmt->execute([
                  ':emp_id' => $eid,
                  ':ptype'  => $payment_type,
                  ':pid'    => $payment_ref_id,
                  ':narr'   => $narration,
                  ':branch' => $branch,
                  ':pdate'  => $payment_date,
                  ':m'      => $salary_month,
                  ':y'      => $salary_year,
                  ':update_d' => $updated_date
              ]);

              $count++;
          }

          // 7. Commit Transaction
          $conn->commit();

          if($count > 0) {
              $message = "<div class='alert alert-success border-0 bg-success alert-dismissible fade show'>
                            <div class='text-white'><strong>Success!</strong> Recorded payments for <strong>$count</strong> employees.</div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
          } else {
              $message = "<div class='alert alert-warning border-0 bg-warning alert-dismissible fade show'>
                            <div class='text-dark'><strong>No Pending Payments Found.</strong> <br>Either all employees in this category are already paid, or no salary sheet exists for this month.</div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
          }

      } catch (Exception $e) {
          $conn->rollBack(); // Undo changes if error occurs
          $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show'>
                        <div class='text-white'>Error: " . $e->getMessage() . "</div>
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
      }
  } 
?>
<!doctype html>
<html lang="en" class="semi-dark">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    
    <link href="assets/css/dark-theme.css" rel="stylesheet" />
    <link href="assets/css/semi-dark.css" rel="stylesheet" />
    <link href="assets/css/header-colors.css" rel="stylesheet" />
    
    <title>Payment Entry</title>
  </head>
  <body>
    
  <div class="wrapper">
    <?php include'system/header.php'?>

    <div class="page-content-wrapper">
      <div class="page-content">

        <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
          <div class="breadcrumb-title pe-3">Record Payments</div>
          <div class="ps-3 border-start">
             <span class="text-secondary small">Process Salary & OT Disbursements</span>
          </div>
        </div>
        <hr/>

        <div class="row">
          <div class="col-xl-10 mx-auto">
             
             <?php echo $message; ?>

             <div class="card border-top border-0 border-4 border-primary">
               <div class="card-body p-4">
                 
                 <div class="d-flex align-items-center justify-content-between mb-4">
                    <div>
                        <h5 class="mb-0 text-primary">Bulk Payment Entry</h5>
                        <p class="mb-0 text-secondary">Record transaction details for employees after salary generation.</p>
                    </div>
                    <div class="fs-1 text-primary"><i class="bi bi-cash-stack"></i></div>
                 </div>
                 <hr class="mb-4" />

                 <form class="row g-4 needs-validation" novalidate method="post">
                    
                    <div class="col-md-6">
                      <label class="form-label fw-bold">Payment For (Category)</label>  
                      <select class="form-select" name="payment_category" required>
                        <option value="">--- Select Category ---</option>
                        <option value="Regular Bank Sheet">Regular Bank Sheet (Salary)</option>
                        <option value="Regular Cheque Sheet">Regular Cheque Sheet (Salary)</option>
                        <option value="OT Bank Sheet">OT Bank Sheet</option>
                        <option value="OT Cheque Sheet">OT Cheque Sheet</option>
                      </select>
                    </div>

                    <div class="col-md-6">
                      <label class="form-label fw-bold">Payment Mode</label>  
                      <select class="form-select" name="payment_type" required>
                        <option value="">--- Select Mode ---</option>
                        <option value="Bank Transfer">Bank Transfer / NEFT</option>
                        <option value="Cheque Payment">Cheque Payment</option>
                        <option value="RTGS">RTGS</option>
                        <option value="Cash">Cash</option>
                      </select>
                    </div>

                    <div class="col-md-6">
                      <label class="form-label fw-bold">Transaction / Cheque No.</label>
                      <input type="text" class="form-control" name="payment_id" placeholder="e.g. UTR12345678" required>
                    </div>

                    <div class="col-md-6">
                      <label class="form-label fw-bold">Payment Date</label>
                      <input type="date" class="form-control" name="payment_date" required value="<?php echo date('Y-m-d'); ?>">
                      <div class="form-text text-muted">
                        Salary will be processed for the <strong>Previous Month</strong> relative to this date.
                      </div>
                    </div>
                    
                    <div class="col-md-12">
                      <label class="form-label fw-bold">Narration / Remarks</label>
                      <textarea class="form-control" name="narration" rows="3" placeholder="Enter batch details or notes..."></textarea>
                    </div>
                    
                    <div class="col-12 mt-3">
                      <div class="d-grid">
                        <button class="btn btn-primary py-2 fw-bold" type="submit" name="submit" onclick="return confirm('This will update employee salary records as PAID. Continue?');">
                            <i class="bi bi-save2-fill me-2"></i>Record Payment
                        </button>
                      </div>
                    </div>

                 </form>
               </div>
             </div>

          </div>
        </div>

      </div>
    </div>

<?php include'system/footer.php'?>