<?php
ob_start(); 
session_start();

// 1. SECURE ERROR REPORTING
// Only show errors on localhost. Hide them in production to prevent path leakage.
if ($_SERVER['SERVER_NAME'] === 'localhost' || $_SERVER['SERVER_NAME'] === '127.0.0.1') {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php"); die();
} 

require_once 'system/conn.php';

// --- Helper Functions ---
function cleanName($name) {
    if (empty($name)) return '';
    $name = trim($name);
    $name = str_replace('(', ' (', $name); 
    $name = mb_convert_case($name, MB_CASE_TITLE, "UTF-8"); 
    $name = preg_replace_callback('/\((.*?)\)/', function($matches) {
        return '(' . strtoupper($matches[1]) . ')';
    }, $name);
    return trim(preg_replace('/\s+/', ' ', $name));
}

if (isset($_POST['submit'])) {

    try {
        // =========================================================
        // PHASE 1: PREPARE DATA (CPU Work - No Database Lock yet)
        // =========================================================
        
        $e_name       = cleanName($_POST['e_name']);
        $fname        = cleanName($_POST['fname']);
        $mname        = cleanName($_POST['mname'] ?? '');
        $husband_wife = cleanName($_POST['husband_wife'] ?? '');
        $bank_name    = cleanName($_POST['bank_name'] ?? '');
        
        $e_doj        = $_POST['e_doj']; 
        $dob          = $_POST['dob'];
        $designation  = $_POST['designation'];
        $addr         = trim($_POST['addr']);
        $bank_ac_no   = trim($_POST['bank_ac_no']);
        $bank_ifsc    = strtoupper(trim($_POST['bank_ifsc']));
        $pan_card     = strtoupper(trim($_POST['pan_card']));
        $uan_no       = trim($_POST['uan_no'] ?? '');
        $esic_no      = trim($_POST['esic_no'] ?? '');
        $mobile_num   = trim($_POST['mobile_num']);
        $alt_mob_no   = trim($_POST['alt_mob_no'] ?? '');
        
        // Format Aadhar (Force XXXX XXXX XXXX)
        $raw_aadhar = preg_replace('/[^0-9]/', '', $_POST['aadhar_num']);
        $aadhar_num = (strlen($raw_aadhar) == 12) ? trim(chunk_split($raw_aadhar, 4, ' ')) : $raw_aadhar;
        
        // Clean Salary
        $salary = str_replace(',', '', $_POST['salary']);
        if($salary === '') $salary = 0;

        $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'   : '';

        $branch       = $_SESSION['branch'];
        $status       = 1;
        $updated_date = date('Y-m-d');

        // Quick Duplicate Check (No Lock)
        $check_dup = $conn->prepare("SELECT e_id FROM emp_details WHERE (LOWER(e_name) = LOWER(?) AND dob = ?) OR (LOWER(e_name) = LOWER(?) AND LOWER(fname) = LOWER(?))");
        $check_dup->execute([$e_name, $dob, $e_name, $fname]);
        if($check_dup->rowCount() > 0) {
            throw new Exception("Duplicate Employee found! Check Name and DOB.");
        }

        // =========================================================
        // PHASE 2: TRANSACTION (High Speed - Database Locked)
        // =========================================================
        $conn->beginTransaction();

        // A. LOCK & GENERATE ID (SQL MAX METHOD)
        $stmt_id = $conn->prepare("
            SELECT MAX(CAST(SUBSTRING_INDEX(e_id, '/', -1) AS UNSIGNED)) AS max_num
            FROM emp_details
            WHERE e_id LIKE 'UTC/%'
            FOR UPDATE
        ");
        $stmt_id->execute();
        $row = $stmt_id->fetch(PDO::FETCH_ASSOC);

        $nextNum = ($row && $row['max_num'] !== null) ? ((int)$row['max_num'] + 1) : 1001; 
        $e_id = 'UTC/' . str_pad($nextNum, 4, '0', STR_PAD_LEFT);

        // B. INSERT DATA (Empty profile initially)
        $stmt = $conn->prepare("
            INSERT INTO emp_details (
                e_id, profile, 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 (
                ?, '', ?, ?, ?, ?, 
                ?, ?, ?, ?,
                ?, ?, ?, ?,
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?, ?, ?,
                ?, ?, ?
            )
        ");

        $stmt->execute([
            $e_id, $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
        ]);

        // C. COMMIT (Lock Released)
        $conn->commit();
        
        // =========================================================
        // PHASE 3: FILE UPLOAD (Only if image selected)
        // =========================================================
        $msg = "Employee Added Successfully! ID: $e_id";
        
        if (!empty($_FILES['profile']['name'])) {
            $uploadDir = 'assets/images/employee/';
            if (!file_exists($uploadDir)) { mkdir($uploadDir, 0777, true); }

            $allowedExt = ['jpg', 'jpeg', 'png', 'webp'];
            $ext = strtolower(pathinfo($_FILES['profile']['name'], PATHINFO_EXTENSION));

            if (in_array($ext, $allowedExt)) {
                $safe_id = str_replace('/', '', $e_id);
                $profile_img = 'emp-' . $safe_id . '-' . time() . '.' . $ext;
                
                if(move_uploaded_file($_FILES['profile']['tmp_name'], $uploadDir . $profile_img)){
                    $updateImg = $conn->prepare("UPDATE emp_details SET profile = ? WHERE e_id = ?");
                    $updateImg->execute([$profile_img, $e_id]);
                } else {
                    $msg .= " (Warning: Image upload failed, but data saved.)";
                }
            } else {
                 $msg .= " (Warning: Invalid image format. Data saved without image.)";
            }
        }

        echo "<script>alert('$msg'); window.location.href='all-employees.php';</script>";

    } catch (Exception $e) {
        if ($conn->inTransaction()) { $conn->rollBack(); }
        echo "<script>alert('Error: " . $e->getMessage() . "'); window.history.back();</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" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <title>Add Employee</title>
    <style>
      .select2-container .select2-selection--single {
        display: block; width: 100%; padding: .375rem .75rem;
        font-size: 1rem; height:auto; color: #212529!important;
        background-color: #fff; border: 1px solid #ced4da; border-radius: .25rem;
      }
    </style>
  </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">Add Employee</div>
          </div>

          <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" onsubmit="return validateForm(event)">

    <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="https://placehold.co/200x200/000000/FFFFFF/?text=Upload"
                     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">Optional (JPG, PNG)</small>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-body">
                <h6 class="mb-3 text-secondary border-bottom pb-2">Payroll & Settings</h6>
                
                <div class="mb-4">
                    <label class="form-label text-success fw-bold small">Gross Salary</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text bg-success text-white">₹</span>
                        <input type="number" class="form-control border-success" name="salary" id="salary" min="0" step="0.01" placeholder="0.00">
                    </div>
                </div>

                <div class="d-flex flex-column">
                    <div class="side-switch">
                        <label class="form-check-label">Overtime</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="over" value="yes" checked>
                        </div>
                    </div>
                    <div class="side-switch">
                        <label class="form-check-label">Conveyance</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="con" value="yes">
                        </div>
                    </div>
                    <div class="side-switch">
                        <label class="form-check-label">Medical</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="med" value="yes">
                        </div>
                    </div>
                    
                    <div class="side-switch border-bottom-0 pb-0">
                        <div class="d-flex align-items-center w-100 justify-content-between">
                            <div class="d-flex align-items-center">
                                <label class="form-check-label me-2">PF</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="pf" value="y" checked>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <label class="form-check-label me-2">ESI</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" name="esi" value="y" checked>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

        <div class="alert alert-light border shadow-sm text-center">
             <div class="text-primary fs-4 mb-1"><i class="bi bi-info-circle-fill"></i></div>
             <div class="text-secondary small">ID Auto-generated<br>(e.g. UTC/xxxx)</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>
                <small class="text-muted">Fields marked with <span class="text-danger">*</span> are mandatory</small>
            </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" id="e_name" required placeholder="Full Name">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Designation <span class="text-danger">*</span></label>
                        <select class="form-select 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>

                    <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>
                    </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" id="dob" max="<?= date('Y-m-d'); ?>" onblur="validateField(this)" required>
                    </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" id="mobile_num" 
                               maxlength="10" placeholder="10 Digit No"
                               pattern="[6-9][0-9]{9}" 
                               oninput="this.value = this.value.replace(/[^0-9]/g, '').substring(0, 10)" 
                               onblur="validateField(this)" required>
                    </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" id="e_doj" max="<?= date('Y-m-d'); ?>" onblur="validateField(this)" required>
                    </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">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Spouse Name</label>
                        <input type="text" class="form-control" name="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" id="alt_mob_no" 
                               maxlength="10" placeholder="10 Digit No"
                               pattern="[6-9][0-9]{9}" 
                               oninput="this.value = this.value.replace(/[^0-9]/g, '').substring(0, 10)" onblur="validateField(this)">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Aadhar Number</label>
                        <input type="text" class="form-control" name="aadhar_num" id="aadhar_num" 
                               maxlength="14" placeholder="XXXX XXXX XXXX"
                               oninput="this.value = this.value.replace(/[^0-9 ]/g, '').substring(0, 14)" onblur="validateField(this)">
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">Residential Address</label>
                        <textarea class="form-control" name="addr" rows="1" placeholder="Address..."></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow-sm mb-3"> <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">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Account No</label>
                        <input type="text" class="form-control" name="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" id="bank_ifsc" style="text-transform:uppercase">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">PAN Number</label>
                        <input type="text" class="form-control" name="pan_card" id="pan_card" style="text-transform:uppercase">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">UAN No</label>
                        <input type="text" class="form-control" name="uan_no">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">ESIC No</label>
                        <input type="text" class="form-control" name="esic_no">
                    </div>
                    
                </div>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-center gap-3">
                    <button class="btn btn-primary btn-lg px-5" type="submit" name="submit" value="submit">
                        <i class="bi bi-check-circle-fill me-2"></i>Save Employee
                    </button>
                    <button type="reset" class="btn btn-outline-secondary btn-lg px-5">
                        <i class="bi bi-arrow-counterclockwise me-2"></i>Reset
                    </button>
                </div>
            </div>
        </div>

    </div> </form>

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

    <?php include 'system/footer.php'; ?>
    
    <script>
// 1. Central Validation Logic (Used by both Submit and Blur)
function getFieldError(id) {
    let value = document.getElementById(id).value.trim();
    let today = new Date();
    today.setHours(0, 0, 0, 0);

    // MOBILE CHECK
    if (id === 'mobile_num') {
        let regex = /^[6-9]\d{9}$/;
        if (!regex.test(value)) return "Mobile: Must be 10 digits & start with 6-9.";
    }

    // ALT MOBILE CHECK
    if (id === 'alt_mob_no' && value.length > 0) {
        let regex = /^[6-9]\d{9}$/;
        if (!regex.test(value)) return "Alt Mobile: Must be 10 digits & start with 6-9.";
    }

    // DOB CHECK
    if (id === 'dob' && value) {
        let date = new Date(value);
        let year = date.getFullYear();
        if (date > today) return "DOB: Cannot be in the future.";
        if (year < 1900 || year > today.getFullYear()) return "DOB: Invalid Year.";
        
        // Age Calc
        let age = today.getFullYear() - year;
        let m = today.getMonth() - date.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < date.getDate())) age--;
        
        if (age < 18) return "DOB: Underage (Must be 18+).";
        if (age > 100) return "DOB: Invalid Age (Over 100).";
    }

    // DOJ CHECK
    if (id === 'e_doj' && value) {
        let date = new Date(value);
        let year = date.getFullYear();
        if (date > today) return "Joining Date: Cannot be in the future.";
        if (year < 2000) return "Joining Date: Must be year 2000 or later.";
    }

    // AADHAR CHECK
    if (id === 'aadhar_num' && value.length > 0) {
        // Remove spaces for check
        let clean = value.replace(/\s/g, '');
        if (!/^\d{12}$/.test(clean)) return "Aadhar: Must be exactly 12 digits.";
    }

    return null; // No error
}

// 2. Immediate Validation on Blur (Leaving the box)
function validateField(input) {
    let error = getFieldError(input.id);
    if (error) {
        // Show browser's native error bubble
        input.setCustomValidity(error);
        input.reportValidity();
        // Clear it immediately after interaction so it doesn't get stuck
        input.oninput = function() { this.setCustomValidity(''); };
    } else {
        input.setCustomValidity('');
    }
}

// 3. Final Validation on Submit (Shows ALL errors)
function validateForm(event) {
    let errors = [];
    let fields = ['e_name', 'mobile_num', 'alt_mob_no', 'dob', 'e_doj', 'aadhar_num'];
    
    fields.forEach(function(id) {
        let input = document.getElementById(id);
        if(input) {
            let err = getFieldError(id);
            if (err) {
                errors.push(err);
                // Mark field as invalid for browser UI
                input.setCustomValidity(err);
            } else {
                input.setCustomValidity('');
            }
        }
    });

    if (errors.length > 0) {
        // Join all errors with a new line
        alert("Please fix the following errors:\n\n" + errors.join("\n"));
        return false; // Stop submission
    }

    return true; // Allow submission
}
</script>
</body>
</html>