<?php
include "auth.php";
checkPermission(['admin','manager','staff']);
require_once "db.php";
ini_set('display_errors', 0); // set 1 for debug temporarily


// Directory for uploaded photos
$uploadDir = __DIR__ . '/uploads/employees/';
$uploadWebDir = 'uploads/employees/'; // relative path for src in HTML

if (!is_dir($uploadDir)) {
    @mkdir($uploadDir, 0755, true);
}

/* -------------------------
   Handle Create / Edit
---------------------------- */
$message = "";
$message_type = "";

function handleImageUpload($fileInputName, $existingFilename = null) {
    global $uploadDir, $uploadWebDir;
    if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
        return $existingFilename; // keep existing
    }
    $f = $_FILES[$fileInputName];
    if ($f['error'] !== UPLOAD_ERR_OK) return $existingFilename;

    $allowed = ['image/jpeg','image/png','image/webp','image/gif'];
    if (!in_array(mime_content_type($f['tmp_name']), $allowed)) return $existingFilename;

    // unique filename
    $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
    $name = 'emp_' . time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
    $dest = $uploadDir . $name;
    if (!move_uploaded_file($f['tmp_name'], $dest)) {
        return $existingFilename;
    }

    // optionally: resize / sanitize image here

    // delete previous file if existed and different
    if ($existingFilename && is_file($uploadDir . $existingFilename) && $existingFilename !== $name) {
        @unlink($uploadDir . $existingFilename);
    }

    return $name;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Gather fields
    $action = $_POST['action'];
    $employee_name = trim($_POST['employee_name'] ?? '');
    $designation_id = intval($_POST['designation_id'] ?? 0);
    $father_name = trim($_POST['father_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $family_phone = trim($_POST['family_phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $join_date = $_POST['join_date'] ?? null;
    $gender = $_POST['gender'] ?? null;
    $blood_group = $_POST['blood_group'] ?? null;
    $nid = trim($_POST['nid'] ?? '');
    $dob = $_POST['dob'] ?? null;
    $base_salary = floatval($_POST['base_salary'] ?? 0);
    $status = in_array($_POST['status'] ?? 'Active', ['Active','Inactive']) ? $_POST['status'] : 'Active';

    if ($action === 'create') {
    if ($employee_name === '' || $designation_id <= 0) {
        $message = "Please provide name and designation.";
        $message_type = "error";
    } else {
        $photo = handleImageUpload('photo', null);

        $stmt = $conn->prepare("INSERT INTO employees 
        (employee_name, designation_id, father_name, phone, family_phone, email, address, join_date, gender, blood_group, nid, dob, base_salary, status, photo) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        if (!$stmt) {
            die("Prepare failed: " . $conn->error);
        }

        $stmt->bind_param(
            "sisssssssssssss",
            $employee_name, $designation_id, $father_name, $phone, $family_phone, $email, $address, $join_date, $gender, $blood_group, $nid, $dob, $base_salary, $status, $photo
        );

        if ($stmt->execute()) {
            $message = "✅ Employee created.";
            $message_type = "success";
        } else {
            $message = "Error: " . $stmt->error;
            $message_type = "error";
        }
        $stmt->close();
    }
    header("Location: employee.php?msg=" . urlencode($message));
    exit();
}


    if ($action === 'edit') {
        $employee_id = intval($_POST['employee_id'] ?? 0);
        if ($employee_id <= 0) {
            $message = "Invalid employee id";
            $message_type = "error";
        } else {
            // fetch existing photo name
            $photoExisting = null;
            $q = $conn->prepare("SELECT photo FROM employees WHERE employee_id=?");
            $q->bind_param("i",$employee_id);
            $q->execute();
            $res = $q->get_result();
            if ($r = $res->fetch_assoc()) $photoExisting = $r['photo'];
            $q->close();

            // handle image upload (replace if new)
            $photo = handleImageUpload('photo', $photoExisting);

            $stmt = $conn->prepare("UPDATE employees SET employee_name=?, designation_id=?, father_name=?, phone=?, family_phone=?, email=?, address=?, join_date=?, gender=?, blood_group=?, nid=?, dob=?, base_salary=?, status=?, photo=? WHERE employee_id=?");
            $stmt->bind_param("sissssssssssdssi", $employee_name, $designation_id, $father_name, $phone, $family_phone, $email, $address, $join_date, $gender, $blood_group, $nid, $dob, $base_salary, $status, $photo, $employee_id);
            if ($stmt->execute()) {
                $message = "✅ Employee updated.";
                $message_type = "success";
            } else {
                $message = "Error: " . $stmt->error;
                $message_type = "error";
            }
            $stmt->close();
        }
        header("Location: employee.php?msg=" . urlencode($message));
        exit();
    }
}

/* -------------------------
   Handle Delete
---------------------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        // Optionally ensure no dependent records (payments/loans) - here we simply delete employee and photo
        $q = $conn->prepare("SELECT photo FROM employees WHERE employee_id=?");
        $q->bind_param("i",$id);
        $q->execute();
        $res = $q->get_result();
        $photo = null;
        if ($r = $res->fetch_assoc()) $photo = $r['photo'];
        $q->close();

        $stmt = $conn->prepare("DELETE FROM employees WHERE employee_id=?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            if ($photo && is_file($uploadDir . $photo)) @unlink($uploadDir . $photo);
            $message = "✅ Employee deleted.";
            $message_type = "success";
        } else {
            $message = "Error deleting employee.";
            $message_type = "error";
        }
        $stmt->close();
    }
    header("Location: employee.php?msg=" . urlencode($message));
    exit();
}

/* -------------------------
   Fetch Designations & Employees
---------------------------- */
$designations = $conn->query("SELECT designation_id, title FROM designation ORDER BY title ASC");

$search = isset($_GET['search']) ? trim($_GET['search']) : "";
$sql = "SELECT e.*, d.title AS designation_title FROM employees e LEFT JOIN designation d ON e.designation_id = d.designation_id";
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $sql .= " WHERE e.employee_name LIKE '%$s%' OR e.phone LIKE '%$s%' OR e.email LIKE '%$s%'";
}
$sql .= " ORDER BY e.employee_id DESC";
$employees = $conn->query($sql);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Employees</title>
<link rel="stylesheet" href="css/style.css" />
<style>
/* small inline styles to match your theme */
.container { max-width:1100px; margin:0 auto; }
.table { width:100%; border-collapse:collapse; }
.table th, .table td { border:1px solid #e6edf3; padding:8px; text-align:left; vertical-align:top; }
.form-row { display:flex; gap:12px; flex-wrap:wrap;margin-bottom: 0; }
.form-group { flex:1; min-width:160px; }
.modal { display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.6); padding-top:60px; }
.modal-content { background:#fff; margin:auto; width: 800px; max-width:900px; border-radius:8px; padding:30px; position:relative; }
.close { position:absolute; right:12px; top:10px; cursor:pointer; }
.preview { width:60px; height:60px; object-fit:cover; border-radius:6px; border:1px solid #ddd; }
.alert { padding:12px 16px; border-radius:6px; margin-bottom:12px; text-align:center; }
.alert.success { background:#d1fae5; color:#065f46; border:1px solid #10b981; }
.alert.error { background:#fee2e2; color:#991b1b; border:1px solid #ef4444; }
.modal-content button{
    width: 100%;
    padding: 12px;
}
.modal-content input{
    box-sizing: border-box;
}
</style>
</head>
<body>
<?php include("global/header.php"); ?>

<main class="main">
  <header class="topbar">
    <button class="hamburger" id="hamburger">☰</button>
    <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Employees</div>
    <?php include("global/notify.php"); ?>
    <div class="profile">
      <button class="profile-btn" id="profileBtn"><span>Welcome <?= htmlspecialchars($_SESSION['username']) ?></span><img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" /></button>
      <nav class="dropdown" id="profileDropdown"><a href="profile.php">Profile Settings</a><a href="users.php">Users Settings</a><a href="logout.php">Logout</a></nav>
    </div>
  </header>

  <section class="content">
    <div class="container">
      <?php if (!empty($_GET['msg'])): ?>
        <div class="alert success"><?= htmlspecialchars($_GET['msg']) ?></div>
      <?php endif; ?>

<div class="filter-box">
    <form method="get" class="flex-box">
        <div class="form-group">
            <input
                type="text"
                name="search"
                placeholder="Search name/phone/email"
                value="<?= htmlspecialchars($search) ?>"
            />
        </div>
        <div class="form-group">
            <button class="btn">🔎 Search</button>
        </div>
    </form>
    <div class="flex-box">
        <div class="form-group">
            <button class="btn" onclick="openCreateModal()">✚ Add Employee</button>
        </div>
        <div class="form-group">
            <a class="btn filter-reset-btn" href="employee.php">↻ Reset</a>
        </div>
    </div>
</div>
  

      <table class="table">
        <thead>
          <tr>
            <th>#</th>
            <th>Photo</th>
            <th>Name</th>
            <th>Designation</th>
            <th>Phone</th>
            <th>Join Date</th>
            <th>Base Salary</th>
            <th>Status</th>
            <th style="text-align:center;">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($employees && $employees->num_rows > 0): $i=1; while($emp = $employees->fetch_assoc()): ?>
          <tr>
            <td><?= $i++; ?></td>
            <td>
              <?php if ($emp['photo'] && is_file($uploadDir . $emp['photo'])): ?>
                <img src="<?= htmlspecialchars($uploadWebDir . $emp['photo']) ?>" class="preview" alt="photo" />
              <?php else: ?>
                <img src="https://via.placeholder.com/80x80?text=No+Photo" class="preview" alt="no photo" />
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($emp['employee_name']); ?><br><small><?= htmlspecialchars($emp['email']); ?></small></td>
            <td><?= htmlspecialchars($emp['designation_title']); ?></td>
            <td><?= htmlspecialchars($emp['phone']); ?></td>
            <td><?= htmlspecialchars($emp['join_date']); ?></td>
            <td style="text-align:right;"><?= number_format($emp['base_salary'],2); ?></td>
            <td><?= htmlspecialchars($emp['status']); ?></td>
            <td style="text-align:center;">
              <button class="btn" type="button" onclick='openEditModal(<?= json_encode($emp, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>Edit</button>
              <a class="btn btn-danger" href="?delete=<?= (int)$emp['employee_id'] ?>" onclick="return confirm('Delete this employee?')">Delete</a>
            </td>
          </tr>
          <?php endwhile; else: ?>
            <tr><td colspan="9" style="text-align:center;color:#6b7280;">No employees found</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </section>
</main>

<!-- Create Modal -->
<div id="createModal" class="modal" aria-hidden="true">
  <div class="modal-content">
    <span class="close" onclick="closeModal('createModal')">&times;</span>
    <h3>Create Employee</h3>
    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="action" value="create">
      <div class="form-row">
        <div class="form-group">
          <label>Employee Name *</label>
          <input type="text" name="employee_name" required>
        </div>
        <div class="form-group">
          <label>Designation *</label>
          <select name="designation_id" required>
            <option value="">-- Select --</option>
            <?php if ($designations) while($d = $designations->fetch_assoc()): ?>
              <option value="<?= (int)$d['designation_id'] ?>"><?= htmlspecialchars($d['title']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="form-group">
            <label>Father Name</label>
            <input type="text" name="father_name">
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
            <label>Phone</label>
            <input type="text" name="phone">
        </div>
        <div class="from-group">
            <label>Family Phone (Emergency)</label>
            <input type="text" name="family_phone">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email">
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
            <label>Address</label>
            <textarea name="address" rows="2"></textarea>
        </div>
        <div class="form-group">
            <label>Join Date</label>
            <input type="date" name="join_date">
        </div>
        <div class="form-group">
            <label>Gender</label>
          <select name="gender">
            <option value="">--</option><option>Male</option><option>Female</option><option>Other</option>
          </select>
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
            <label>Blood Group</label
            ><input type="text" name="blood_group">
        </div>
        <div class="form-group">
            <label>NID / Smart ID</label>
            <input type="text" name="nid">
        </div>
        <div class="form-group">
            <label>Date of Birth</label>
            <input type="date" name="dob">
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
            <label>Base Salary</label>
            <input type="number" name="base_salary" step="0.01" value="0">
        </div>
        <div class="form-group"><label>Status</label>
          <select name="status">
            <option>Active</option><option>Inactive</option>
          </select>
        </div>
        <div class="form-group">
          <label>Photo</label>
          <input type="file" name="photo" accept="image/*" onchange="previewCreatePhoto(this)">
          <div style="margin-top:6px;"><img id="createPhotoPreview" class="preview" src="images/user.png" alt="preview" /></div>
        </div>
      </div>


      <div class="form-row">
        
      </div>

      <div style="margin-top:10px;"><button class="btn">Save Employee</button></div>
    </form>
  </div>
</div>

<!-- Edit modal -->
<div id="editModal" class="modal" aria-hidden="true">
  <div class="modal-content">
    <span class="close" onclick="closeModal('editModal')">&times;</span>
    <h3>Edit Employee</h3>
    <form method="post" enctype="multipart/form-data" id="editForm">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="employee_id" id="edit_employee_id">
      <div class="form-row">
        <div class="form-group"><label>Employee Name *</label><input type="text" name="employee_name" id="edit_employee_name" required></div>
        <div class="form-group"><label>Designation *</label>
          <select name="designation_id" id="edit_designation_id" required>
            <option value="">-- Select --</option>
            <?php
            // re-fetch designations for edit dropdown
            $design2 = $conn->query("SELECT designation_id, title FROM designation ORDER BY title ASC");
            if ($design2) while($dd = $design2->fetch_assoc()):
            ?>
              <option value="<?= (int)$dd['designation_id'] ?>"><?= htmlspecialchars($dd['title']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="form-group"><label>Father Name</label><input type="text" name="father_name" id="edit_father_name"></div>
      </div>

      <div class="form-row">
        <div class="form-group"><label>Phone</label><input type="text" name="phone" id="edit_phone"></div>
        <div class="form-group"><label>Family Phone</label><input type="text" name="family_phone" id="edit_family_phone"></div>
        <div class="form-group"><label>Email</label><input type="email" name="email" id="edit_email"></div>
      </div>

      <div class="form-row">
        <div class="form-group"><label>Address</label><textarea name="address" id="edit_address" rows="2"></textarea></div>
        <div class="form-group"><label>Join Date</label><input type="date" name="join_date" id="edit_join_date"></div>
        <div class="form-group"><label>Gender</label>
          <select name="gender" id="edit_gender"><option value="">--</option><option>Male</option><option>Female</option><option>Other</option></select>
        </div>
      </div>


      <div class="form-row">
        <div class="form-group"><label>Blood Group</label><input type="text" name="blood_group" id="edit_blood_group"></div>
        <div class="form-group"><label>NID / Smart ID</label><input type="text" name="nid" id="edit_nid"></div>
        <div class="form-group"><label>Date of Birth</label><input type="date" name="dob" id="edit_dob"></div>
      </div>

      <div class="form-row">
        <div class="form-group"><label>Base Salary</label><input type="number" name="base_salary" id="edit_base_salary" step="0.01"></div>
        <div class="form-group"><label>Status</label><select name="status" id="edit_status"><option>Active</option><option>Inactive</option></select></div>
        <div class="form-group">
          <label>Photo</label>
          <input type="file" name="photo" accept="image/*" onchange="previewEditPhoto(this)">
          <div style="margin-top:6px;"><img id="editPhotoPreview" class="preview" src="https://via.placeholder.com/80x80?text=Preview" /></div>
        </div>
      </div>


      <div style="margin-top:10px;"><button class="btn">Update Employee</button></div>
    </form>
  </div>
</div>

<script>
// modal handlers
function openCreateModal() { document.getElementById('createModal').style.display = 'block'; }
function openEditModal(data) {
  // populate edit form from server-supplied object
  document.getElementById('edit_employee_id').value = data.employee_id || '';
  document.getElementById('edit_employee_name').value = data.employee_name || '';
  document.getElementById('edit_designation_id').value = data.designation_id || '';
  document.getElementById('edit_father_name').value = data.father_name || '';
  document.getElementById('edit_phone').value = data.phone || '';
  document.getElementById('edit_family_phone').value = data.family_phone || '';
  document.getElementById('edit_email').value = data.email || '';
  document.getElementById('edit_address').value = data.address || '';
  document.getElementById('edit_join_date').value = data.join_date || '';
  document.getElementById('edit_gender').value = data.gender || '';
  document.getElementById('edit_blood_group').value = data.blood_group || '';
  document.getElementById('edit_nid').value = data.nid || '';
  document.getElementById('edit_dob').value = data.dob || '';
  document.getElementById('edit_base_salary').value = data.base_salary || '';
  document.getElementById('edit_status').value = data.status || 'Active';
  // preview photo if exists
  if (data.photo) {
    document.getElementById('editPhotoPreview').src = '<?= $uploadWebDir ?>' + data.photo;
  } else {
    document.getElementById('editPhotoPreview').src = 'https://via.placeholder.com/80x80?text=Preview';
  }
  document.getElementById('editModal').style.display = 'block';
}
function closeModal(id) { document.getElementById(id).style.display = 'none'; }
window.onclick = function(e) { if (e.target.classList.contains('modal')) e.target.style.display = 'none'; }

// image preview functions
function previewCreatePhoto(inp) {
  const el = document.getElementById('createPhotoPreview');
  if (inp.files && inp.files[0]) el.src = URL.createObjectURL(inp.files[0]);
}
function previewEditPhoto(inp) {
  const el = document.getElementById('editPhotoPreview');
  if (inp.files && inp.files[0]) el.src = URL.createObjectURL(inp.files[0]);
}
</script>

<script>
            // Sidebar accordion & profile dropdown (same behavior as your other pages)
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault();
                    const currentItem = btn.parentElement;
                    const isOpen = currentItem.classList.contains("open");
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });
            document
                .querySelectorAll(".submenu")
                .forEach((ul) => ul.addEventListener("click", (e) => e.stopPropagation()));
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => sidebar.classList.toggle("active"));
            document.addEventListener("click", (e) => {
                if (
                    !sidebar.contains(e.target) &&
                    !hamburger.contains(e.target) &&
                    sidebar.classList.contains("active")
                ) {
                    sidebar.classList.remove("active");
                }
            });
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>
</body>
</html>
