<?php 
    session_start();
    if(!$_SESSION['id']){
        header('location:index.php');
    }
    require_once '../system/conn.php';
?>
<?php 
if (isset($_POST['submit'])) {

    // Employee ID (already full like UTC/1002)
    $e_id = $_POST['e_id'];

    // Basic details
    $e_name         = $_POST['e_name'];
    $fname          = $_POST['fname'];
    $mname          = $_POST['mname'] ?? '';
    $husband_wife   = $_POST['husband_wife'] ?? '';
    $e_doj          = $_POST['e_doj'];
    $dob            = $_POST['dob'];
    $designation    = $_POST['designation'];

    // Identity & contact
    $aadhar_num     = $_POST['aadhar_num'];
    $mobile_num     = $_POST['mobile_num'];
    $alt_mob_no     = $_POST['alt_mob_no'] ?? '';
    $addr           = $_POST['addr'];

    // Bank & salary
    $bank_ac_no     = $_POST['bank_ac_no'];
    $bank_ifsc      = $_POST['bank_ifsc'];
    $bank_name      = $_POST['bank_name'];
    $pan_card       = $_POST['pan_card'];
    $salary         = $_POST['salary'];
    $uan_no         = $_POST['uan_no'] ?? '';
    $esic_no        = $_POST['esic_no'] ?? '';

    // Checkbox flags (safe)
    $ot   = isset($_POST['over']) ? 'yes' : '';
    $con  = isset($_POST['con'])  ? 'y'   : '';
    $med  = isset($_POST['med'])  ? 'y'   : '';
    $pf   = isset($_POST['pf'])   ? 'y'   : '';
    $esi  = isset($_POST['esi'])  ? 'y'   : '';

    // System fields
    $branch        = $_POST['branch'];
    $status        = 1;
    $updated_date  = date('Y-m-d');

    /* ===============================
       IMAGE UPLOAD (OPTIONAL)
    =============================== */
   $profile = '';

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

    if (in_array($ext, $allowedExt)) {
        $profile = 'emp-' . date('Ymd-His') . '.' . $ext;

        move_uploaded_file(
            $_FILES['profile']['tmp_name'],
            $uploadDir . $profile
        );
    } else {
        echo "<script>alert('Invalid image type. Only JPG, JPEG, PNG, WEBP allowed.');</script>";
        $profile = '';
    }
}


    /* ===============================
       INSERT QUERY
    =============================== */
    $stmt = $conn->prepare("
        INSERT INTO emp_details (
            e_id, image, e_name, fname, mname, husband_wife,
            e_doj, 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 (
            ?, ?, ?, ?, ?, ?,
            ?, ?, ?, ?,
            ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?, ?,
            ?, ?, ?
        )
    ");

    $result = $stmt->execute([
        $e_id,
        $profile,        // image
        $e_name,
        $fname,
        $mname,
        $husband_wife,
        $e_doj,
        $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
    ]);

    if ($result) {
        echo "<script>alert('Employee added successfully');</script>";
        echo "<script>window.location.href='all-employees.php';</script>";
    } else {
        echo "<script>alert('Insert failed');</script>";
    }
}
?>
<!doctype html>
<html lang="en" class="semi-dark">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <!-- loader-->
      <link href="assets/css/pace.min.css" rel="stylesheet" />
      <script src="assets/js/pace.min.js"></script>

    <!--plugins-->
    <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" />

    <!-- CSS Files -->
    <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">

    <!--Theme Styles-->
    <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>UTCPL</title>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
     .select2-container .select2-selection--single   {
                display: block;
    width: 100%;
    padding: .375rem .75rem;
    font-size: 1rem;
        height:auto;
    font-weight: 400;
    line-height: 1.5;
    color: #212529!important;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
        }
    </style>
  </head>
  <body>
    

 <!--start wrapper-->
    <div class="wrapper">
    <?php include'system/header.php'?>
    <!--end top header-->


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

             <!--start breadcrumb-->
            <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
              <div class="breadcrumb-title pe-3">Add Employee</div>
            </div>
            <!--end breadcrumb-->


            <div class="row">
              <div class="col-xl-12 mx-auto">
                
                <div class="card">
                  <div class="card-body">
                    <div class="p-4 border rounded">
                        
                      <form class="row g-3 needs-validation" novalidate method="post" enctype="multipart/form-data" action="">
                        <h6 class="mb-0 text-uppercase">Employee Details :</h6>
                        <hr/>
                        <div class="col-md-12">
                          <select class="form-control" name="e_id" hidden>
            <?php
            $stmt = $conn->prepare("SELECT e_id FROM `emp_details` ORDER BY e_id DESC LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();

            if ($row) {
                $parts = explode('/', $row['e_id']);
                $new_id = $parts[0] . '/' . ((int)$parts[1] + 1);
            } else {
                $new_id = "UTC/1001";
            }
            ?>
            <option value="<?= $new_id ?>"><?= $new_id ?></option>
        </select>
                        </div>
                        <!-- PASSPORT SIZE IMAGE (OPTIONAL) -->
    <div class="col-md-4">
        
        <img id="previewImage"
             src="https://placehold.co/200x200/000000/FFFFFF/?text=NO+IMAGE"
             alt="Preview"
             class="text-center mx-auto img-thumbnail mb-2"
             style="max-width:120px;height:150px;object-fit:cover;">
             <div>
                 <label class="form-label text-left">Passport Size Photo<small class="text-muted">(Optional)</small></label>
        <input type="file"
               class="form-control"
               name="profile"
               accept="image/*"
               onchange="previewPassport(this)">

             </div>
             
    </div>
<div class="col-md-8 row">
    <!-- EMPLOYEE NAME -->
    <div class="col-md-12">
        <label class="form-label">Employee Name <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="e_name" required placeholder="Enter Employee Name">
    </div>

    
<div class="col-md-6">
                          <label for="validationCustom01" class="form-label">Employee Branch Name</label>
                          <select class="form-control" id="validationCustom01" name="branch" placeholder="Branch" required>
                              <option value="">---Select Branch---</option>
                              <?php
                                $stmt = $conn->prepare("SELECT * FROM `branch` ");
                                $stmt->execute();
                                $sql1 = $stmt->fetchAll();
                                foreach($sql1 as $row) 
                                { ?>
                                  <option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>  
                              <?php } ?>
                          </select>
                          <div class="valid-feedback">Enter Branch!</div>
                        </div>
<!-- DESIGNATION -->
<div class="col-md-6">
    <label class="form-label">Employee Designation <span class="text-danger">*</span></label>
    <select class="form-control select2" 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']; ?>"><?= $row['name']; ?></option>
        <?php } ?>
    </select>
</div>
    <!-- FATHER NAME -->
    <div class="col-md-6">
        <label class="form-label">Father Name <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="fname" required>
    </div>

    <!-- MOTHER NAME -->
    <div class="col-md-6">
        <label class="form-label">Mother Name</label>
        <input type="text" class="form-control" name="mname">
    </div>
</div>
    
                        <div class="col-md-6">
                          <label for="validationCustom01" class="form-label">Husband/ Wife Name</label>
                          <input type="text" class="form-control" id="validationCustom01" placeholder="Husband/ Wife Name" name="husband_wife" required>
                          <div class="valid-feedback">Enter Husband/ Wife Name !</div>
                        </div>
                        
                        
                        <div class="col-md-6">
                          <label for="validationCustom01" class="form-label">Joining Date</label>
                          <input type="date" class="form-control" id="validationCustom01" placeholder="Joining Date" name="e_doj" required>
                          <div class="valid-feedback">Enter Valid Date!</div>
                        </div>
                        <div class="col-md-6">
                          <label for="validationCustom01" class="form-label">DOB</label>
                          <input type="date" class="form-control" id="validationCustom01" placeholder="DOB" name="dob" required>
                          <div class="valid-feedback">Enter Valid Date!</div>
                        </div>
                        <div class="col-md-6">
                          <label for="validationCustom01" class="form-label">Aadhar Number</label>
                          <input type="text" class="form-control" id="validationCustom01" placeholder="Enter Aadhar Number" name="aadhar_num" required>
                          <div class="valid-feedback">Enter Aadhar Number!</div>
                        </div>
                        <!-- MOBILE -->
    <div class="col-md-6">
        <label class="form-label">Mobile Number <span class="text-danger">*</span></label>
        <input type="tel"
               class="form-control"
               name="mobile_num"
               pattern="[6-9]{1}[0-9]{9}"
               required>
    </div>

    <!-- ALT MOBILE -->
    <div class="col-md-6">
        <label class="form-label">Alternate Mobile Number</label>
        <input type="tel"
               class="form-control"
               name="alt_mob_no"
               pattern="[6-9]{1}[0-9]{9}">
    </div>

    <!-- ADDRESS -->
    <div class="col-md-12">
        <label class="form-label">Address <span class="text-danger">*</span></label>
        <textarea class="form-control" name="addr" rows="4" required></textarea>
    </div>
                        
                        <h6 class="mb-0 text-uppercase">Salary Detail :</h6>
                        <hr/>
                        
                        <!-- BANK DETAILS -->
    <div class="col-md-4">
        <label class="form-label">Bank A/C Number <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="bank_ac_no" required>
    </div>

    <div class="col-md-4">
        <label class="form-label">IFSC Code <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="bank_ifsc" required>
    </div>

    <div class="col-md-4">
        <label class="form-label">Bank Name <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="bank_name" required>
    </div>

    <!-- PAN -->
    <div class="col-md-6">
        <label class="form-label">PAN Card <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="pan_card" required>
    </div>

    <!-- SALARY -->
    <div class="col-md-6">
        <label class="form-label">Gross Salary <span class="text-danger">*</span></label>
        <input type="text" class="form-control" name="salary" required>
    </div>

    <!-- OPTIONAL -->
    <div class="col-md-6">
        <label class="form-label">UAN Number</label>
        <input type="text" class="form-control" name="uan_no">
    </div>

    <div class="col-md-6">
        <label class="form-label">ESIC Number</label>
        <input type="text" class="form-control" name="esic_no">
    </div>
                        
                        <div class="col-md-4">
                          <label class="form-check-label" for="validationFormCheck1">Overtime Allowed</label>
                          <input type="checkbox" class="form-check-input" id="validationFormCheck1" name="over" value="yes" required="">
                          <div class="invalid-feedback">Overtime Allowed</div>
                        </div>
                        <div class="col-md-4">
                          <label class="form-check-label" for="validationFormCheck1">Convyance allowance</label>
                          <input type="checkbox" class="form-check-input" id="validationFormCheck1" name="con" value="yes" required="">
                          <div class="invalid-feedback">Convyance allowance</div>
                        </div>
                        <div class="col-md-4">
                          <label class="form-check-label" for="validationFormCheck1">Medical allowance</label>
                          <input type="checkbox" class="form-check-input" id="validationFormCheck1" name="med" value="yes" required="">
                          <div class="invalid-feedback">Medical allowance</div>
                        </div>
                        <div class="col-md-6">
                          <label class="form-check-label" for="validationFormCheck1">PF Allowed</label>
                          <input type="checkbox" class="form-check-input" id="validationFormCheck1" name="pf" value="y" checked required="">
                          <div class="invalid-feedback">PF Allowed</div>
                        </div>
                        <div class="col-md-6">
                          <label class="form-check-label" for="validationFormCheck1">ESI Allowed</label>
                          <input type="checkbox" class="form-check-input" id="validationFormCheck1" name="esi" value="y" checked required="">
                          <div class="invalid-feedback">ESI Allowed</div>
                        </div>
                        
                        
                        <div class="col-12">
                          <button class="btn btn-primary" type="submit" name="submit" value="submit" >Submit form</button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
                
                
              </div>
            </div>
            <!--end row-->


          </div>
          <!-- end page content-->
         </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>

<!-- Include Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    $('.select2').select2({
        placeholder: "---Select Designation---",
        allowClear: true,
        width: '100%'
    });
});
</script>