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

// =========================================================
//  PART 1: AJAX HANDLER
// =========================================================
if(isset($_POST['ajax_fetch']) && isset($_POST['emp_id'])) {
    $e_id = $_POST['emp_id'];
    $current_branch_id = $_SESSION['branch'];

    // 1. SECURITY CHECK
    $check_stmt = $conn->prepare("SELECT e_name FROM emp_details WHERE e_id = ? AND branch = ?");
    $check_stmt->execute([$e_id, $current_branch_id]);
    
    if($check_stmt->rowCount() == 0) {
        echo json_encode([
            'status_html' => '<tr><td colspan="2" class="text-center text-danger">Employee ID not found in your branch.</td></tr>',
            'options' => '<option value="">--- Invalid Employee ---</option>'
        ]);
        exit;
    }

    // 2. Fetch Status
    $current_branches_ids = [];
    $status_rows = '';
    
    $stmt = $conn->prepare("SELECT e.status, b.name, b.id FROM emp_details e JOIN branch b ON e.branch = b.id WHERE e.e_id = ? ORDER BY b.name ASC");
    $stmt->execute([$e_id]);
    $existing_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if(count($existing_data) > 0){
        foreach($existing_data as $row){
            $current_branches_ids[] = $row['id'];
            $badge = ($row['status'] == 1) 
                ? '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Active</span>' 
                : '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Inactive</span>';
            
            $row_class = ($row['id'] == $current_branch_id) ? 'table-primary' : '';
            $branch_label = ($row['id'] == $current_branch_id) ? $row['name'] . ' (Current)' : $row['name'];

            $status_rows .= "<tr class='{$row_class}'><td>{$branch_label}</td><td>{$badge}</td></tr>";
        }
    }

    // 3. Build Options
    $stmt_b = $conn->prepare("SELECT id, name FROM branch ORDER BY name ASC");
    $stmt_b->execute();
    $all_branches = $stmt_b->fetchAll(PDO::FETCH_ASSOC);
    
    $options = '<option value="">--- Select Target Branch ---</option>';
    $available_count = 0;

    foreach($all_branches as $br){
        if(!in_array($br['id'], $current_branches_ids)){
            $options .= '<option value="'.$br['id'].'">'.$br['name'].'</option>';
            $available_count++;
        }
    }

    if($available_count == 0){
        $options = '<option value="">(Employee exists in all branches)</option>';
    }

    echo json_encode(['status_html' => $status_rows, 'options' => $options]);
    exit; 
}

// =========================================================
//  PART 2: FORM SUBMISSION HANDLER
// =========================================================
if(isset($_POST["submit"])) {
    $ename = $_POST['ename']; 
    $target_branch = $_POST['sitename']; 
    $current_branch = $_SESSION['branch'];

    // 1. Fetch Source Data
    $select = $conn->prepare("SELECT * FROM `emp_details` WHERE `e_id`=? AND `branch`=? LIMIT 1");
    $select->execute([$ename, $current_branch]);
    $row = $select->fetch(PDO::FETCH_ASSOC);
    
    if($row) {
        $check = $conn->prepare("SELECT * FROM `emp_details` WHERE `e_id`=? AND `branch`=?");
        $check->execute([$ename, $target_branch]);
        
        $log_action = ""; 
        $success = false;
        $message = "";

        if($check->rowCount() == 0) {
            // INSERT (Copy)
            $updated_date = date('Y-m-d');
            $sql = "INSERT INTO `emp_details`
            (`e_id`, `e_name`, `fname`, `mname`, `husband_wife`, `e_doj`, `profile`, `aadhar_num`, `mobile_num`, `alt_mob_no`, `bank_ac_no`, `bank_ifsc`, `bank_name`, `designation`, `dob`, `pan_card`, `uan_no`, `addr`, `salary`, `ot`, `con`, `med`, `pf`, `esi`, `esic_no`, `branch`, `status`, `updated_date`) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $insert = $conn->prepare($sql);
            $res = $insert->execute([
                $row['e_id'], $row['e_name'], $row['fname'], $row['mname'], $row['husband_wife'], $row['e_doj'], 
                $row['profile'], $row['aadhar_num'], $row['mobile_num'], $row['alt_mob_no'], $row['bank_ac_no'], 
                $row['bank_ifsc'], $row['bank_name'], $row['designation'], $row['dob'], $row['pan_card'], 
                $row['uan_no'], $row['addr'], $row['salary'], $row['ot'], $row['con'], $row['med'], 
                $row['pf'], $row['esi'], $row['esic_no'], $target_branch, $row['status'], $updated_date
            ]);

            if($res) {
                $success = true;
                $log_action = "Copy";
                $message = "Transfer successful! Employee copied to new branch.";
            }
        } else {
            // UPDATE (Reactivate)
            $update = $conn->prepare("UPDATE `emp_details` SET `status`=1 WHERE `e_id`=? AND `branch`=?");
            if($update->execute([$ename, $target_branch])) {
                $success = true;
                $log_action = "Reactivate";
                $message = "Employee already existed in target branch. Status set to Active.";
            }
        }

        // --- FIXED LOGGING BLOCK (Run BEFORE Redirect) ---
        if($success) {
            try {
                // Get Performed By (Fallback to 'Unknown' if session missing)
                $performed_by = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'Unknown User'; 

                $log_sql = "INSERT INTO `transfer_log` (`emp_id`, `from_branch`, `to_branch`, `action_type`, `performed_by`, `transfer_date`) VALUES (?, ?, ?, ?, ?, NOW())";
                $log_stmt = $conn->prepare($log_sql);
                $log_stmt->execute([$ename, $current_branch, $target_branch, $log_action, $performed_by]);
                
                // Alert and Redirect ONLY after logging is done
                echo '<script>alert("'.$message.'"); window.location.href="branch-transfer.php";</script>';
            } catch (Exception $e) {
                // If log fails, still show success but maybe alert error (Optional)
                echo '<script>alert("Transfer Done, but Log Failed: '.$e->getMessage().'"); window.location.href="branch-transfer.php";</script>';
            }
        }
        // ------------------------------------------------

    } else {
        echo '<script>alert("Error: You do not have permission to transfer this employee.");</script>';
    }
}
?>

<!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="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <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>Branch Transfer</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">Employee Branch Transfer</div>
                <div class="ms-auto">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0 p-0">
                            <li class="breadcrumb-item"><a href="all-employees.php"><i class="bx bx-user"></i></a></li>
                            <li class="breadcrumb-item active">Transfer</li>
                        </ol>
                    </nav>
                </div>
              </div>
              <hr/>

              <div class="row">
                  <div class="col-xl-9 mx-auto">
                    <div class="card shadow-sm border-0">
                      <div class="card-body p-4">
                        
                          <form action="" method="post">
                            <div class="row g-4">
                                
                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><i class="bi bi-person-badge me-2"></i>Select Employee</label>
                                    <input list="brow" id="ename" class="form-control" name="ename" placeholder="Start typing Name or ID..." required autocomplete="off">
                                    <datalist id="brow">
                                      <?php 
                                        $stmt = $conn->prepare("SELECT e_id, e_name FROM emp_details WHERE branch=? AND status='1' GROUP BY e_id");
                                        $stmt->execute([$_SESSION['branch']]);
                                        foreach($stmt->fetchAll() as $row) { 
                                            echo '<option value="'.$row['e_id'].'">'.$row['e_name'].' ('.$row['e_id'].')</option>';
                                        } 
                                      ?>
                                    </datalist>
                                    <div class="form-text">Choose an employee from your branch to copy.</div>
                                </div>

                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><i class="bi bi-geo-alt-fill me-2"></i>Transfer To</label>
                                    <select class="form-select" id="target_branch" name="sitename" required>
                                        <option value="">(Select an employee first)</option>
                                    </select>
                                    <div class="form-text">Only shows available branches.</div>
                                </div>
                                
                                <div class="col-12 mt-4 text-center">
                                    <button type="submit" name="submit" class="btn btn-primary px-5">
                                        <i class="bi bi-arrow-left-right me-2"></i> Process Transfer
                                    </button>
                                </div>
                            </div>
                           </form>

                           <div class="mt-5" id="status_section" style="display:none;">
                               <div class="alert alert-light border">
                                   <h6 class="text-primary mb-3"><i class="bi bi-info-circle me-2"></i>Current Employment Status</h6>
                                   <div class="table-responsive">
                                       <table class="table table-bordered table-sm mb-0 align-middle">
                                           <thead class="table-light">
                                               <tr>
                                                   <th>Branch Name</th>
                                                   <th style="width: 150px;">Status</th>
                                               </tr>
                                           </thead>
                                           <tbody id="status_body">
                                               </tbody>
                                       </table>
                                   </div>
                               </div>
                           </div>

                      </div>
                    </div>
                  </div>
                </div>
            
             </div>
        </div>
    <?php include 'system/footer.php' ?>
    </div>
    
    <script src="assets/js/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('#ename').on('input change', function() {
            var empId = $(this).val();
            
            if(empId.length > 2) {
                $.ajax({
                    type: 'POST',
                    url: 'branch-transfer.php', 
                    data: {
                        ajax_fetch: 1, 
                        emp_id: empId
                    },
                    dataType: 'json',
                    success: function(response){
                        $('#status_section').fadeIn();
                        $('#status_body').html(response.status_html);
                        $('#target_branch').html(response.options);
                    },
                    error: function() {
                        console.log('Error fetching employee details.');
                    }
                });
            } else {
                $('#status_section').hide();
                $('#target_branch').html('<option value="">(Select an employee first)</option>');
            }
        });
    });
    </script>
  </body>
</html>