<?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"]))
  {
      $selected_employees = $_POST['payment_for']; // Array of Emp IDs
      $payment_type       = $_POST['payment_type'];
      $payment_id         = trim($_POST['payment_id']);
      $narration          = trim($_POST['narration']);
      $payment_date       = $_POST['payment_date'];
      $branch             = $_SESSION['branch'];
      $updated_date       = date("Y-m-d");

      // Calculate Salary Month (Previous Month relative to Payment Date)
      $timestamp = strtotime("-1 month", strtotime($payment_date));
      $salary_month = date("m", $timestamp);
      $salary_year  = date("Y", $timestamp);

      if(!empty($selected_employees)) {
          try {
              $conn->beginTransaction();
              $count = 0;

              // Prepare Statements outside loop for performance
              $stmt_insert = $conn->prepare("INSERT INTO payment_tbl 
                  (payment_for, payment_type, payment_id, narration, branch, payment_date, month, year, updated_date) 
                  VALUES (:eid, :ptype, :pid, :narr, :br, :pdate, :m, :y, :udate)");

              $stmt_update = $conn->prepare("UPDATE emp_salary SET payment_status = '1' 
                  WHERE emp_id = :eid AND month = :m AND year = :y AND branch = :br");

              // We delete from rev_payment_tbl because the issue is now resolved
              $stmt_delete = $conn->prepare("DELETE FROM rev_payment_tbl 
                  WHERE emp_id = :eid AND branch = :br LIMIT 1");

              foreach($selected_employees as $emp_id) {
                  
                  // 1. Insert New Payment Record
                  $stmt_insert->execute([
                      ':eid'   => $emp_id,
                      ':ptype' => $payment_type,
                      ':pid'   => $payment_id,
                      ':narr'  => $narration,
                      ':br'    => $branch,
                      ':pdate' => $payment_date,
                      ':m'     => $salary_month,
                      ':y'     => $salary_year,
                      ':udate' => $updated_date
                  ]);

                  // 2. Mark Salary as Paid
                  $stmt_update->execute([
                      ':eid' => $emp_id,
                      ':m'   => $salary_month,
                      ':y'   => $salary_year,
                      ':br'  => $branch
                  ]);

                  // 3. Remove from Returned List (Issue Resolved)
                  $stmt_delete->execute([
                      ':eid' => $emp_id,
                      ':br'  => $branch
                  ]);

                  $count++;
              }

              $conn->commit();
              $message = "<div class='alert alert-success border-0 bg-success alert-dismissible fade show'>
                            <div class='text-white'>Success! Re-processed payments for <strong>$count</strong> employees.</div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";

          } catch (Exception $e) {
              $conn->rollBack();
              $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>";
          }
      } else {
          $message = "<div class='alert alert-warning border-0 bg-warning alert-dismissible fade show'>
                        <div class='text-dark'>Please select at least one employee.</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/plugins/select2/css/select2.min.css" rel="stylesheet" />
    <link href="assets/plugins/select2/css/select2-bootstrap4.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>Individual 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">Payment Correction</div>
            <div class="ps-3 border-start">
                <span class="text-secondary small">Re-issue returned/failed payments</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-warning">
               <div class="card-body p-4">
                 
                 <div class="d-flex align-items-center justify-content-between mb-4">
                    <div>
                        <h5 class="mb-0 text-warning">Individual Payment Entry</h5>
                        <p class="mb-0 text-secondary">Select employees from the returned list to pay them again.</p>
                    </div>
                    <div class="fs-1 text-warning"><i class="bi bi-arrow-counterclockwise"></i></div>
                 </div>
                 <hr class="mb-4" />

                 <form class="row g-4 needs-validation" novalidate method="post">
                    
                    <div class="col-md-12">
                      <label class="form-label fw-bold">Select Returned Employees <span class="text-danger">*</span></label>
                      <select class="multiple-select" data-placeholder="Choose employees..." multiple="multiple" name="payment_for[]" required>
                        <?php 
                            // Optimized Query: JOIN to get names instantly
                            // Only fetching distinct employees from the Return Table
                            $sql = "SELECT DISTINCT r.emp_id, e.e_name 
                                    FROM rev_payment_tbl r 
                                    LEFT JOIN emp_details e ON r.emp_id = e.e_id AND r.branch = e.branch
                                    WHERE r.branch = :br 
                                    ORDER BY e.e_name ASC";
                            $stmt = $conn->prepare($sql);
                            $stmt->execute([':br' => $_SESSION['branch']]);
                            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        ?>
                            <option value="<?php echo $row['emp_id']; ?>">
                                <?php echo $row['e_name'] . " (" . $row['emp_id'] . ")"; ?>
                            </option>
                        <?php } ?>
                      </select>
                      <div class="form-text">List shows only employees marked as "Returned".</div>
                    </div>

                    <div class="col-md-4">
                      <label class="form-label fw-bold">New Payment Mode <span class="text-danger">*</span></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-4">
                      <label class="form-label fw-bold">New Transaction ID <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" name="payment_id" placeholder="e.g. UTR_NEW_123" required>
                    </div>

                    <div class="col-md-4">
                      <label class="form-label fw-bold">Payment Date <span class="text-danger">*</span></label>
                      <input type="date" class="form-control" name="payment_date" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    
                    <div class="col-md-12">
                      <label class="form-label fw-bold">Narration / Remarks</label>
                      <textarea class="form-control" name="narration" rows="3" placeholder="e.g. Re-payment for Jan Salary (prev return)"></textarea>
                    </div>
                    
                    <div class="col-12 mt-4">
                      <div class="d-grid">
                        <button class="btn btn-warning py-2 fw-bold text-dark" type="submit" name="submit">
                            <i class="bi bi-check2-circle me-2"></i>Process Re-Payment
                        </button>
                      </div>
                    </div>

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

          </div>
        </div>

      </div>
    </div>

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

    <script src="assets/plugins/select2/js/select2.min.js"></script>
    <script>
        $('.multiple-select').select2({
            theme: 'bootstrap4',
            width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
            placeholder: $(this).data('placeholder'),
            allowClear: true
        });
    </script>