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

// ==========================================
//  HANDLE UPDATE SUBMISSION
// ==========================================
if (isset($_POST['submit'])) {

    // 1. Employee Details
    $e_id = $_POST['e_id'];
    $e_name = $_POST['e_name'];
    $fname = $_POST['fname'];
    $mname = $_POST['mname'];
    $husband_wife = $_POST['husband_wife'];
    $e_doj = $_POST['e_doj'];
    $designation = $_POST['designation'];
    $dob = $_POST['dob'];
    $pan_card = $_POST['pan_card'];
    $addr = $_POST['addr'];
    $aadhar_num = $_POST['aadhar_num'];
    $mobile_num = $_POST['mobile_num'];
    $alt_mob_no = $_POST['alt_mob_no'];
    $bank_ac_no = $_POST['bank_ac_no'];
    $bank_ifsc = $_POST['bank_ifsc'];
    $bank_name = $_POST['bank_name'];
    $uan_no = $_POST['uan_no'];
    $esic_no = $_POST['esic_no'];
    $salary = $_POST['salary'];
    $branch = $_SESSION['branch'];
    $updated_date = date('Y-m-d');

    // 2. Checkbox Normalization
    // (Matches your specific DB values: 'yes' for OT, 'y' for others)
    $ovx  = !empty($_POST['over']) ? 'yes' : '';
    $conx = !empty($_POST['con'])  ? 'y'   : '';
    $medx = !empty($_POST['med'])  ? 'y'   : '';
    $pfx  = !empty($_POST['pf'])   ? 'y'   : '';
    $esix = !empty($_POST['esi'])  ? 'y'   : '';

    // 3. Image Upload Handling (Smart)
    // If new file uploaded, use it. Otherwise, keep the old one.
    $profile = $_POST['old_image']; // Default to existing

    if (!empty($_FILES['profile']['name'])) {
        $uploadDir = 'assets/images/employee/';
        $allowedExt = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($_FILES['profile']['name'], PATHINFO_EXTENSION));

        if (in_array($ext, $allowedExt)) {
            $new_filename = 'emp-' . date('Ymd-His') . '.' . $ext;
            if(move_uploaded_file($_FILES['profile']['tmp_name'], $uploadDir . $new_filename)){
                $profile = $new_filename; // Update variable only on success
            }
        } else {
            echo "<script>alert('Invalid image type. Only JPG, JPEG, PNG, WEBP allowed.');</script>";
        }
    }
    
    // 4. Update Query
    // We update both 'image' and 'profile' columns to maintain compatibility
    $query = "UPDATE emp_details SET 
              image = ?, profile = ?, e_name = ?, fname = ?, mname = ?, husband_wife = ?, e_doj = ?, designation = ?, dob = ?, pan_card = ?, addr = ?,
              aadhar_num = ?, mobile_num = ?, alt_mob_no = ?, bank_ac_no = ?, bank_ifsc = ?, bank_name = ?, ot = ?, 
              esi = ?, con = ?, pf = ?, med = ?, uan_no = ?, esic_no = ?, salary = ?, updated_date = ?
              WHERE e_id = ? AND branch = ?";

    $stmt = $conn->prepare($query);
    $result = $stmt->execute([
       $profile, $profile, $e_name, $fname, $mname, $husband_wife, $e_doj, $designation, $dob, $pan_card, $addr,
       $aadhar_num, $mobile_num, $alt_mob_no, $bank_ac_no, $bank_ifsc, $bank_name, $ovx,
       $esix, $conx, $pfx, $medx, $uan_no, $esic_no, $salary, $updated_date,
       $e_id, $branch
    ]);

    if ($result) {
        echo "<script>alert('Employee details updated successfully.'); window.location.href = 'all-employees.php';</script>";
    } else {
        echo "<script>alert('Failed to update employee details.');</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>Edit Employee Data</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">Human Resources</div>
            <div class="ps-3">
                <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" aria-current="page">Edit Employee</li>
                    </ol>
                </nav>
            </div>
        </div>

        <?php
          // FETCH EXISTING DATA
          if(isset($_GET['id'])){
              $sth = $conn->prepare("SELECT * FROM `emp_details` where `e_id`=? AND `branch`=?");
              $sth->execute([$_GET['id'], $_SESSION['branch']]);
              $user = $sth->fetch(PDO::FETCH_ASSOC);

              if(!$user){
                  echo '<div class="alert alert-danger">Employee not found or access denied.</div>';
                  exit;
              }
              
              // Handle Image Path
              $img_source = 'https://placehold.co/200x200/000000/FFFFFF/?text=NO+IMAGE';
              if(!empty($user['profile']) && file_exists('assets/images/employee/'.$user['profile'])){
                  $img_source = 'assets/images/employee/'.$user['profile'];
              } elseif(!empty($user['image']) && file_exists('assets/images/employee/'.$user['image'])){
                   $img_source = 'assets/images/employee/'.$user['image'];
              }
          }
        ?>

        <form class="row g-3 needs-validation" novalidate method="post" enctype="multipart/form-data">
            
            <input type="hidden" name="e_id" value="<?php echo $user['e_id']; ?>">
            <input type="hidden" name="old_image" value="<?php echo !empty($user['profile']) ? $user['profile'] : $user['image']; ?>">

            <div class="col-xl-3 col-lg-4">
                
                <div class="card shadow-sm">
                    <div class="card-body text-center">
                        <h6 class="mb-3 text-secondary">Profile Picture</h6>
                        <img id="previewImage"
                             src="<?php echo $img_source; ?>"
                             alt="Preview"
                             class="img-thumbnail rounded-circle mb-3"
                             style="width:140px; height:140px; object-fit:cover;">
                        
                        <div class="mb-2">
                            <input type="file" class="form-control form-control-sm" name="profile" accept="image/*" onchange="previewPassport(this)">
                        </div>
                        <small class="text-muted">Change Photo (Optional)</small>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <button class="btn btn-primary btn-lg" type="submit" name="submit" value="submit">
                                <i class="bi bi-check-circle-fill me-2"></i>Update Data
                            </button>
                            <a href="all-employees.php" class="btn btn-outline-secondary">
                                <i class="bi bi-arrow-left me-2"></i>Cancel
                            </a>
                        </div>
                    </div>
                </div>

                <div class="alert alert-light border shadow-sm">
                    <div class="d-flex align-items-center">
                        <div class="fs-3 text-primary"><i class="bi bi-person-badge"></i></div>
                        <div class="ms-3">
                            <div class="text-secondary small">Employee ID:</div>
                            <div class="fw-bold text-dark"><?php echo $user['e_id']; ?></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-9 col-lg-8">
                
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h5 class="mb-0 text-primary"><i class="bi bi-person-lines-fill me-2"></i>Core Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            
                            <div class="col-md-4">
                                <label class="form-label">Employee Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="e_name" required value="<?php echo $user['e_name']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Designation <span class="text-danger">*</span></label>
                                <select class="form-select" name="designation" required>
                                    <option value="">Select Designation...</option>
                                    <?php
                                    $stmt = $conn->prepare("SELECT * FROM `designation`");
                                    $stmt->execute();
                                    foreach ($stmt->fetchAll() as $row) { ?>
                                        <option value="<?= $row['name']; ?>" <?php echo ($user['designation'] == $row['name']) ? 'selected' : ''; ?>>
                                            <?= $row['name']; ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Father's Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="fname" required value="<?php echo $user['fname']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Date of Birth <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="dob" required value="<?php echo $user['dob']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Mobile Number <span class="text-danger">*</span></label>
                                <input type="tel" class="form-control" name="mobile_num" required value="<?php echo $user['mobile_num']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Joining Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="e_doj" required value="<?php echo $user['e_doj']; ?>">
                            </div>

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

                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h5 class="mb-0"><i class="bi bi-house-door me-2"></i>Personal Details</h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            
                            <div class="col-md-4">
                                <label class="form-label">Mother's Name</label>
                                <input type="text" class="form-control" name="mname" value="<?php echo $user['mname']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Spouse Name</label>
                                <input type="text" class="form-control" name="husband_wife" value="<?php echo $user['husband_wife']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Alt. Mobile</label>
                                <input type="tel" class="form-control" name="alt_mob_no" value="<?php echo $user['alt_mob_no']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Aadhar Number</label>
                                <input type="text" class="form-control" name="aadhar_num" value="<?php echo $user['aadhar_num']; ?>">
                            </div>

                            <div class="col-md-8">
                                <label class="form-label">Residential Address</label>
                                <textarea class="form-control" name="addr" rows="4"><?php echo $user['addr']; ?></textarea>
                            </div>

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

                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h5 class="mb-0"><i class="bi bi-wallet2 me-2"></i>Financial & Statutory</h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            
                            <div class="col-md-4">
                                <label class="form-label">Bank Name</label>
                                <input type="text" class="form-control" name="bank_name" value="<?php echo $user['bank_name']; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Account No</label>
                                <input type="text" class="form-control" name="bank_ac_no" value="<?php echo $user['bank_ac_no']; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">IFSC Code</label>
                                <input type="text" class="form-control" name="bank_ifsc" value="<?php echo $user['bank_ifsc']; ?>">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">PAN Number</label>
                                <input type="text" class="form-control" name="pan_card" value="<?php echo $user['pan_card']; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">UAN No</label>
                                <input type="text" class="form-control" name="uan_no" value="<?php echo $user['uan_no']; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">ESIC No</label>
                                <input type="text" class="form-control" name="esic_no" value="<?php echo $user['esic_no']; ?>">
                            </div>
                            
                            <div class="col-md-4">
                                <label class="form-label text-success fw-bold">Gross Salary</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-success text-white">₹</span>
                                    <input type="text" class="form-control border-success" name="salary" value="<?php echo $user['salary']; ?>">
                                </div>
                            </div>

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

                <div class="card shadow-sm">
                    <div class="card-body">
                        <h6 class="mb-4">Configuration & Allowances</h6>
                        
                        <div class="d-flex flex-wrap gap-5 align-items-center ps-2">
                            
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="over" value="yes" style="transform: scale(1.4);" <?php if($user['ot']=='yes') echo "checked"; ?>>
                                <label class="form-check-label ms-2 fs-6">Overtime</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="con" value="yes" style="transform: scale(1.4);" <?php if($user['con']=='y') echo "checked"; ?>>
                                <label class="form-check-label ms-2 fs-6">Conveyance</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="med" value="yes" style="transform: scale(1.4);" <?php if($user['med']=='y') echo "checked"; ?>>
                                <label class="form-check-label ms-2 fs-6">Medical</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="pf" value="y" style="transform: scale(1.4);" <?php if($user['pf']=='y') echo "checked"; ?>>
                                <label class="form-check-label ms-2 fs-6">PF</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="esi" value="y" style="transform: scale(1.4);" <?php if($user['esi']=='y') echo "checked"; ?>>
                                <label class="form-check-label ms-2 fs-6">ESI</label>
                            </div>

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

            </div>
        </form>

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

  <?php include 'system/footer.php'; ?>
  
  <script>
  function previewPassport(input) {
      if (input.files && input.files[0]) {
          const reader = new FileReader();
          reader.onload = function (e) {
              document.getElementById('previewImage').src = e.target.result;
          };
          reader.readAsDataURL(input.files[0]);
      }
  }
  </script>
  </body>
</html>