<?php
// Database Connection
require_once 'connection.php';
$conn = Database::connect();

/* ---------------------------------------------
   INSERT APPLICATION
---------------------------------------------- */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['job_id']) && !isset($_POST['update'])) {

    $job_id = $_POST['job_id'];

    // Fetch Job Title
    $stmt2 = $conn->prepare("SELECT title FROM job_posts WHERE id = ?");
    $stmt2->execute([$job_id]);
    $row = $stmt2->fetch(PDO::FETCH_ASSOC);
    $jobTitle = $row ? $row['title'] : "";

    try {
        $sql = "INSERT INTO apply (
            job_id, job_title,
            position_applied, desired_salary, date_available, current_position, nic_number, desired_city,
            applicant_name, father_or_husband_name, current_address, permanent_address,
            city_district, total_experience, home_phone, cell_phone, email, whatsapp_no,
            degree, year_passed, division, board,
            company_name, position_of_job, main_duty1, duration_of_duty
        ) VALUES (
            :job_id, :job_title,
            :position_applied, :desired_salary, :date_available, :current_position, :nic_number, :desired_city,
            :applicant_name, :father_or_husband_name, :current_address, :permanent_address,
            :city_district, :total_experience, :home_phone, :cell_phone, :email, :whatsapp_no,
            :degree, :year_passed, :division, :board,
            :company_name, :position_of_job, :main_duty1, :duration_of_duty
        )";

        $stmt = $conn->prepare($sql);
        $stmt->execute([
            ':job_id' => $job_id,
            ':job_title' => $jobTitle,
            ':position_applied' => $_POST['position_applied'] ?? null,
            ':desired_salary' => $_POST['desired_salary'] ?? null,
            ':date_available' => $_POST['date_available'] ?? null,
            ':current_position' => $_POST['current_position'] ?? null,
            ':nic_number' => $_POST['nic_number'] ?? null,
            ':desired_city' => $_POST['desired_city'] ?? null,
            ':applicant_name' => $_POST['applicant_name'] ?? null,
            ':father_or_husband_name' => $_POST['father_or_husband_name'] ?? null,
            ':current_address' => $_POST['current_address'] ?? null,
            ':permanent_address' => $_POST['permanent_address'] ?? null,
            ':city_district' => $_POST['city_district'] ?? null,
            ':total_experience' => $_POST['total_experience'] ?? null,
            ':home_phone' => $_POST['home_phone'] ?? null,
            ':cell_phone' => $_POST['cell_phone'] ?? null,
            ':email' => $_POST['email'] ?? null,
            ':whatsapp_no' => $_POST['whatsapp_no'] ?? null,
            ':degree' => $_POST['degree'] ?? null,
            ':year_passed' => $_POST['year_passed'] ?? null,
            ':division' => $_POST['division'] ?? null,
            ':board' => $_POST['board'] ?? null,
            ':company_name' => $_POST['company_name'] ?? null,
            ':position_of_job' => $_POST['position_of_job'] ?? null,
            ':main_duty1' => $_POST['main_duty1'] ?? null,
            ':duration_of_duty' => $_POST['duration_of_duty'] ?? null
        ]);

        echo "<script>alert('Application submitted successfully!'); window.location='applyjob.php';</script>";
        exit;

    } catch (PDOException $e) {
        echo "<pre>SQL Error: " . $e->getMessage() . "</pre>";
    }
}


/* ---------------------------------------------
   UPDATE APPLICATION
---------------------------------------------- */
if (isset($_POST['update'])) {

    $id       = $_POST['id'];
    $company  = $_POST['company_name'];
    $position = $_POST['position_applied'];
    $name     = $_POST['applicant_name'];
    $email    = $_POST['email'];

    $stmt = $conn->prepare("
        UPDATE apply 
        SET company_name = ?, 
            position_applied = ?, 
            applicant_name = ?, 
            email = ?
        WHERE id = ?
    ");

    $stmt->execute([$company, $position, $name, $email, $id]);

    echo "<script>alert('Updated successfully'); window.location='applyjob.php';</script>";
    exit;
}


/* ---------------------------------------------
   DELETE
---------------------------------------------- */
if (isset($_GET['delete_id'])) {

    $delete_id = $_GET['delete_id'];

    $stmt = $conn->prepare("DELETE FROM apply WHERE id = ?");
    $stmt->execute([$delete_id]);

    echo "<script>alert('Deleted successfully'); window.location='applyjob.php';</script>";
    exit;
}


/* ---------------------------------------------
   FETCH ALL APPLICATIONS
---------------------------------------------- */
try {
    $stmt = $conn->query("SELECT * FROM apply ORDER BY id DESC");
    $jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $jobs = [];
}
?>


<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Post Job</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
   <link rel="stylesheet" href="./CSS/postjob.css" />
   <!-- <link rel="stylesheet" href="./CSS/applyjob.css" /> -->
   <!-- <link rel="stylesheet" href="./customerlist.css" /> -->
   <style>
        table {
            width: 100%;
            border-collapse: collapse;
            border: none;
            margin-top: 15px;
            background-color: white;
        }

        th,
        td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid gray;
        }

        th {
            background: #4a90e2;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background: rgba(0, 0, 0, 0.5);
        }
       .btn-info{

          background-color: #4a90e2;
       }
        .fa-eye{
          color: white;
        }
        .fa-pen{
          background-color: #007bff;
        }


.modal-content {
  background: #fff;
  margin: 10% auto;
  padding: 25px;
  border-radius: 10px;
  width: 500px;
  max-width: 100%;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

.modal-content h2 {
  margin-bottom: 15px;
  border-bottom: 2px solid #ddd;
  padding-bottom: 8px;
}

.modal-content input {
  width: 100%;
  margin: 6px 0;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.close {
  float: right;
  font-size: 24px;
  cursor: pointer;
  color: #555;
}

.close:hover {
  color: red;
}





.app {
    display: grid;
    grid-template-columns: 280px auto;
    grid-template-rows: 72px auto;
    height: 100vh;
    /* overflow: ; */
}

.sidebar {
    grid-row: 1 / span 2;
    height: 100%;
    overflow-y: auto;
}

.header {
    grid-column: 2;
    height: 70px;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 10px 20px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.main {
    grid-column: 2;
    overflow-y: auto;
    padding: 20px;
    background: #f7f8fc;
    height: calc(100vh - 70px);
}
    </style>

    <style>
/* Modal background */
.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
  transition: 0.3s;
}

/* Modal content card */
.modal-content.delete-card {
  background-color: #fff;
  margin: 10% auto;
  padding: 25px 30px;
  border-radius: 10px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  animation: slideDown 0.3s ease-out;
  text-align: center;
  position: relative;
}

/* Slide-down animation */
@keyframes slideDown {
  from { transform: translateY(-50px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

/* Close button */
.close {
  color: #aaa;
  position: absolute;
  right: 15px;
  top: 10px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  transition: 0.2s;
}
.close:hover {
  color: #000;
}

/* Modal title */
.delete-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 22px;
  font-weight: 600;
  color: #d9534f; /* Red for warning */
}

/* Modal text */
.delete-text {
  font-size: 16px;
  color: #555;
  margin-bottom: 25px;
  line-height: 1.5;
}

/* Action buttons */
.delete-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  flex-wrap: wrap;
}

/* Buttons */
.btn {
  padding: 10px 18px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: 0.2s;
}

.delete-btn {
  background-color: #d9534f;
  color: #fff;
}
.delete-btn:hover {
  background-color: #c9302c;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}
.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* Responsive */
@media (max-width: 480px) {
  .modal-content.delete-card {
    width: 90%;
    padding: 20px;
  }

  .delete-actions {
    flex-direction: column;
  }

  .delete-actions .btn {
    width: 100%;
  }
}



/* Modal background */
.modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.5);
  transition: 0.3s;
}

/* Modal content card */
.modal-content.edit-card {
  background-color: #fff;
  margin: 5% auto;
  padding: 30px 35px;
  border-radius: 12px;
  width: 450px;
  max-width: 90%;
  box-shadow: 0 10px 25px rgba(0,0,0,0.3);
  animation: slideDown 0.3s ease-out;
  position: relative;
}

/* Slide-down animation */
@keyframes slideDown {
  from { transform: translateY(-50px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

/* Close button */
.close {
  color: #aaa;
  position: absolute;
  right: 20px;
  top: 15px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  transition: 0.2s;
}
.close:hover {
  color: #000;
}

/* Modal title */
.edit-title {
  margin-top: 0;
  margin-bottom: 25px;
  font-size: 24px;
  font-weight: 600;
  color: #222;
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
  text-align: center;
}

/* Form styling */
.edit-form {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  font-size: 14px;
}

.form-group input {
  padding: 10px 12px;
  font-size: 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  transition: 0.2s;
}

.form-group input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 5px rgba(0,123,255,0.3);
}

/* Modal footer buttons */
.modal-footer {
  text-align: right;
  margin-top: 20px;
}

.btn.update-btn {
  background-color: #007bff;
  color: #fff;
  padding: 10px 20px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 15px;
  transition: 0.2s;
}

.btn.update-btn:hover {
  background-color: #0069d9;
}

/* Responsive */
@media (max-width: 480px) {
  .modal-content.edit-card {
    width: 90%;
    padding: 20px;
  }

  .modal-footer {
    text-align: center;
  }

  .btn.update-btn {
    width: 100%;
  }
}


</style>

</head>

<body>
    <div class="app" id="app">
       <!-- Sidebar -->
        <?php include 'asidebar.php'; ?>
     <!-- Header -->
   <?php include 'header.php';?>

  <!-- MAin Content -->
    <main class="main">
    <div class="table-header">
    <h3 style="font-weight:600;">Post Job</h3>
    <div class="table-actions">
      <div class="table-search">
        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
        <input type="text" placeholder="Search users…" id="tableSearch">
      </div>
      <!-- <button class="btn btn-sm btn-secondary"><i class="fa-solid fa-filter"></i> Filter</button>
      <button class="btn btn-sm btn-secondary"><i class="fa-solid fa-download"></i> Export</button> -->
    </div>
  </div>
        <!-- <?php if(isset($_GET['msg'])): ?>
            <p style="color:green;"><?= htmlspecialchars($_GET['msg']); ?></p>
        <?php endif; ?> -->

        <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Company</th>
                    <th>Position</th>
                    <th>Application</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>City</th>
                    <!-- <th>Allow</th> -->
                    <th>Phone</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if($jobs): $n=1; foreach($jobs as $job): ?>
                <tr>
                    <td><?= $n++; ?></td>
                    <td><?= htmlspecialchars($job['company_name']); ?></td>
                    <td><?= htmlspecialchars($job['position_applied']); ?></td>
                    <td><?= htmlspecialchars($job['applicant_name']); ?></td>
                    <td><?= htmlspecialchars($job['email']); ?></td>
                    <td><?= htmlspecialchars($job['desired_city']); ?></td>
                    <td><?= htmlspecialchars($job['cell_phone']); ?></td>
                    <!-- <td><?= htmlspecialchars($job['email']); ?></td> -->
                    <!-- <td><?= $u['terms'] ? 'Yes' : 'No'; ?></td> -->
                    <!-- <td><?= intval($u['login_count']); ?></td> -->
                     <!-- <td>
                         <label class="switch">
              <input type="checkbox" <?= $u['allow'] ? 'checked' : ''; ?> onchange="toggleAllow(<?= $u['id']; ?>, this.checked)">
              <span class="slider"></span>
            </label>
                    </td> -->
                    <td>
            <!-- <button class="btn btn-info" onclick='viewJob(<?= json_encode($job); ?>)'><i class="fa-solid fa-eye"></i></button> -->
             <button class="btn btn-info" onclick='viewJob(<?= json_encode($job); ?>)'>
                    <i class="fa-solid fa-eye"></i>
                </button>
           <button class="btn btn-primary" onclick='editJob(<?= json_encode($job); ?>)'><i class="fa-solid fa-pen"></i></button>
            <!-- <form method="POST" style="display:inline;">
              <input type="hidden" name="id" value="<?= $job['id']; ?>"> -->
            <button class="btn btn-danger" onclick="confirmDelete(<?= $job['id']; ?>)"><i class="fa-solid fa-trash"></i></button>
            <!-- </form> -->
          </td>
                </tr>
            <?php endforeach; else: ?>
                <tr><td colspan="7" style="text-align:center;">No users found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
        </div>

<div class="modal" id="viewModal">
  <div class="modal-content">
    <span class="close" onclick="closeModal('viewModal')">&times;</span>
    <h3>User Details</h3>
    <div id="viewBody"></div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('viewModal')">Close</button>
    </div>
  </div>
</div>






        <!-- EDIT MODAL -->
<div class="modal" id="editModal">
  <div class="modal-content edit-card">
    <span class="close" onclick="closeModal('editModal')">&times;</span>
    <h3 class="edit-title">Edit Job</h3>

    <form method="post" class="edit-form">
      <input type="hidden" name="id" id="edit_id">

      <div class="form-group">
        <label for="edit_company_name">Company</label>
        <input type="text" name="company_name" id="edit_company_name" placeholder="Company">
      </div>

      <div class="form-group">
        <label for="edit_position_applied">Position Applied</label>
        <input type="text" name="position_applied" id="edit_position_applied" placeholder="Position Applied">
      </div>

      <div class="form-group">
        <label for="edit_applicant_name">Applicant Name</label>
        <input type="text" name="applicant_name" id="edit_applicant_name" placeholder="Applicant Name">
      </div>

      <div class="form-group">
        <label for="edit_email">Email</label>
        <input type="email" name="email" id="edit_email" placeholder="Email">
      </div>

      <div class="modal-footer">
        <button type="submit" name="update" class="btn update-btn">Update</button>
      </div>
    </form>
  </div>
</div>




        <!-- DELETE MODAL -->
       <div id="deleteModal" class="modal">
  <div class="modal-content delete-card">
    <span class="close" onclick="closeModal('deleteModal')">&times;</span>
    <h2 class="delete-title">Confirm Delete</h2>
    <p class="delete-text">Are you sure you want to delete this job?</p>
    <div class="delete-actions">
      <button id="confirmDeleteBtn" class="btn delete-btn">Yes, Delete</button>
      <button class="btn cancel-btn" onclick="closeModal('deleteModal')">Cancel</button>
    </div>
  </div>
</div>


    </main>
  
    </div>

    <script>

      const searchInput = document.getElementById('tableSearch');
    const table = document.querySelector('table tbody');

    searchInput.addEventListener('keyup', function() {
        const filter = searchInput.value.toLowerCase();
        const rows = table.querySelectorAll('tr');

        rows.forEach(row => {
            // Get the email column (7th column, index 6)
            const emailCell = row.cells[4];
            if (emailCell) {
                const emailText = emailCell.textContent.toLowerCase();
                row.style.display = emailText.includes(filter) ? '' : 'none';
            }
        });
    });

      function viewJob(job) {
    document.getElementById('viewBody').innerHTML = `
        <p><strong>Company:</strong> ${job.company_name}</p>
        <p><strong>Position:</strong> ${job.position_applied}</p>
        <p><strong>Name:</strong> ${job.applicant_name}</p>
        <p><strong>Email:</strong> ${job.email}</p>
        <p><strong>City:</strong> ${job.desired_city}</p>
        <p><strong>Phone:</strong> ${job.cell_phone}</p>
    `;
    document.getElementById('viewModal').style.display = 'block';
}
     function editJob(job) {
    document.getElementById('edit_id').value = job.id;
    document.getElementById('edit_company_name').value = job.company_name;
    document.getElementById('edit_position_applied').value = job.position_applied;
    document.getElementById('edit_applicant_name').value = job.applicant_name;
    document.getElementById('edit_email').value = job.email;

    document.getElementById('editModal').style.display = 'block';
}

        function confirmDelete(id) {
            document.getElementById('confirmDeleteBtn').onclick = function () {
                window.location.href = 'applyjob.php?delete_id=' + id;
            };
            document.getElementById('deleteModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
    </script>

</body>

</html>