<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "Recruitment";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    // FIX (07 Jul 2026): job_openings/job_applications had no org concept
    // at all — added company_id (migration_job_openings_company.sql) and
    // scoped every read/write here to the current org.
    $orgCompanies = orgCompanyIds($db);
    $companyId    = $orgCompanies[0] ?? 0;
    if ($action === "save_job") {
        $id = postInt("id");
        // Confirm the job being edited belongs to this org.
        if ($id) {
            $owned = $db->fetchOne("SELECT id FROM job_openings WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$id], $orgCompanies));
            if (!$owned) { setFlash('error','Job opening not found.'); header("Location: ".BASE_URL."/modules/recruitment/index.php"); exit; }
            $db->execute("UPDATE job_openings SET title=?,department_id=?,designation_id=?,vacancies=?,location_id=?,employment_type=?,experience_min=?,experience_max=?,description=?,status=? WHERE id=?",
                [post("title"),postInt("dept"),postInt("desig"),postInt("vacancies"),postInt("loc"),post("emp_type"),postInt("exp_min"),postInt("exp_max"),post("description"),post("status"),$id]);
        } else {
            $db->execute("INSERT INTO job_openings (company_id,title,department_id,designation_id,vacancies,location_id,employment_type,experience_min,experience_max,description,status,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
                [$companyId,post("title"),postInt("dept"),postInt("desig"),postInt("vacancies"),postInt("loc"),post("emp_type"),postInt("exp_min"),postInt("exp_max"),post("description"),"open",currentUser()["id"]]);
        }
        setFlash("success","Job opening saved.");
    } elseif ($action === "save_candidate") {
        $jobId = postInt("job_id");
        $owned = $db->fetchOne("SELECT id FROM job_openings WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$jobId], $orgCompanies));
        if (!$owned) { setFlash('error','Job opening not found.'); header("Location: ".BASE_URL."/modules/recruitment/index.php"); exit; }
        $db->execute("INSERT INTO job_applications (job_opening_id,candidate_name,candidate_email,candidate_phone,years_experience,current_company,current_ctc,expected_ctc,source,status) VALUES (?,?,?,?,?,?,?,?,?,?)",
            [$jobId,post("name"),post("email"),post("phone"),postInt("exp"),post("current_co"),post("current_ctc"),post("expected_ctc"),post("source"),"applied"]);
        setFlash("success","Candidate added.");
    } elseif ($action === "move_stage") {
        // Confirm the application belongs to a job in this org.
        $app = $db->fetchOne(
            "SELECT ja.id FROM job_applications ja JOIN job_openings jo ON jo.id=ja.job_opening_id WHERE ja.id=? AND jo.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt("id")], $orgCompanies)
        );
        if ($app) {
            $db->execute("UPDATE job_applications SET status=? WHERE id=?", [post("stage"),postInt("id")]);
            setFlash("success","Stage updated.");
        } else {
            setFlash("error","Application not found.");
        }
    }
    header("Location: ".BASE_URL."/modules/recruitment/index.php"); exit;
}

$tab     = $_GET["tab"] ?? "jobs";
// FIX: scope job listing to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'jo.company_id');
$jobs    = $db->fetchAll("SELECT jo.*,d.name AS dept,des.name AS desig,l.name AS location,(SELECT COUNT(*) FROM job_applications WHERE job_opening_id=jo.id) AS apps FROM job_openings jo LEFT JOIN departments d ON d.id=jo.department_id LEFT JOIN designations des ON des.id=jo.designation_id LEFT JOIN locations l ON l.id=jo.location_id WHERE $orgClause ORDER BY jo.created_at DESC", $orgParams);
$depts   = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");
$desigs  = $db->fetchAll("SELECT id,name FROM designations WHERE is_active=1 ORDER BY name");
$locs    = $db->fetchAll("SELECT id,name FROM locations WHERE is_active=1 ORDER BY name");
$selJob  = cleanInt($_GET["job"] ?? 0);
// FIX: reject ?job=<other org's job opening>.
if ($selJob && !in_array($selJob, array_column($jobs, 'id'))) { $selJob = 0; }
$apps    = $selJob ? $db->fetchAll("SELECT * FROM job_applications WHERE job_opening_id=? ORDER BY created_at DESC",[$selJob]) : [];
$editJob = cleanInt($_GET["edit"] ?? 0);
if ($editJob && !in_array($editJob, array_column($jobs, 'id'))) { $editJob = 0; }
$editData = $editJob ? $db->fetchOne("SELECT * FROM job_openings WHERE id=?",[$editJob]) : null;
$stages  = ["applied","screening","shortlisted","interview","offer","hired","rejected"];

include __DIR__ . "/../../includes/header.php";
?>
<div class="pc-tabs mb-3">
  <div class="pc-tab <?=$tab==="jobs"?"active":""?>" onclick="location='?tab=jobs'">Job Openings</div>
  <div class="pc-tab <?=$tab==="add"?"active":""?>" onclick="location='?tab=add'">New Opening</div>
  <?php if($selJob): ?><div class="pc-tab <?=$tab==="candidates"?"active":""?>" onclick="location='?tab=candidates&job=<?=$selJob?>'">Candidates</div><?php endif; ?>
</div>

<?php if($tab==="jobs"): ?>
<div class="pc-card">
  <div class="pc-card-title"><i class="ti ti-briefcase me-2"></i>Job Openings</div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead><tr><th>Title</th><th>Department</th><th>Location</th><th>Type</th><th>Vacancies</th><th>Applications</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
      <?php foreach($jobs as $j): ?>
      <tr>
        <td class="fw-semibold"><?=clean($j["title"])?></td>
        <td><?=clean($j["dept"]??"—")?></td>
        <td><?=clean($j["location"]??"—")?></td>
        <td><?=ucfirst(str_replace("_"," ",$j["employment_type"]))?></td>
        <td><?=$j["vacancies"]?></td>
        <td><a href="?tab=candidates&job=<?=$j["id"]?>" class="badge" style="background:var(--pc-blue-bg);color:var(--pc-blue)"><?=$j["apps"]?> Applied</a></td>
        <td><?=statusBadge($j["status"])?></td>
        <td><a href="?tab=add&edit=<?=$j["id"]?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a></td>
      </tr>
      <?php endforeach; if(!$jobs): ?><tr><td colspan="8" class="text-center text-muted py-3">No job openings</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php elseif($tab==="add"): ?>
<div class="pc-card" style="max-width:680px">
  <div class="pc-card-title"><i class="ti ti-user-plus me-2"></i><?=$editData?"Edit":"New"?> Job Opening</div>
  <form method="POST">
    <?=csrfField()?><input type="hidden" name="action" value="save_job">
    <?php if($editData): ?><input type="hidden" name="id" value="<?=$editData["id"]?>"><?php endif; ?>
    <div class="row g-3">
      <div class="col-12"><label class="pc-label">Job Title</label><input type="text" name="title" class="form-control form-control-sm" value="<?=clean($editData["title"]??"")?>" required></div>
      <div class="col-md-6"><label class="pc-label">Department</label><select name="dept" class="form-select form-select-sm"><option value="">Select</option><?php foreach($depts as $d): ?><option value="<?=$d["id"]?>" <?=($editData["department_id"]??"")==$d["id"]?"selected":""?>><?=clean($d["name"])?></option><?php endforeach; ?></select></div>
      <div class="col-md-6"><label class="pc-label">Designation</label><select name="desig" class="form-select form-select-sm"><option value="">Select</option><?php foreach($desigs as $d): ?><option value="<?=$d["id"]?>" <?=($editData["designation_id"]??"")==$d["id"]?"selected":""?>><?=clean($d["name"])?></option><?php endforeach; ?></select></div>
      <div class="col-md-4"><label class="pc-label">Vacancies</label><input type="number" name="vacancies" class="form-control form-control-sm" value="<?=$editData["vacancies"]??1?>" min="1"></div>
      <div class="col-md-4"><label class="pc-label">Location</label><select name="loc" class="form-select form-select-sm"><option value="">Select</option><?php foreach($locs as $l): ?><option value="<?=$l["id"]?>" <?=($editData["location_id"]??"")==$l["id"]?"selected":""?>><?=clean($l["name"])?></option><?php endforeach; ?></select></div>
      <div class="col-md-4"><label class="pc-label">Employment Type</label><select name="emp_type" class="form-select form-select-sm"><?php foreach(["full_time"=>"Full Time","part_time"=>"Part Time","contract"=>"Contract","intern"=>"Intern"] as $v=>$l): ?><option value="<?=$v?>" <?=($editData["employment_type"]??"")===$v?"selected":""?>><?=$l?></option><?php endforeach; ?></select></div>
      <div class="col-md-3"><label class="pc-label">Min Experience (yrs)</label><input type="number" name="exp_min" class="form-control form-control-sm" value="<?=$editData["experience_min"]??0?>"></div>
      <div class="col-md-3"><label class="pc-label">Max Experience (yrs)</label><input type="number" name="exp_max" class="form-control form-control-sm" value="<?=$editData["experience_max"]??5?>"></div>
      <?php if($editData): ?><div class="col-md-3"><label class="pc-label">Status</label><select name="status" class="form-select form-select-sm"><?php foreach(["open","on_hold","closed"] as $s): ?><option value="<?=$s?>" <?=$editData["status"]===$s?"selected":""?>><?=ucfirst(str_replace("_"," ",$s))?></option><?php endforeach; ?></select></div><?php endif; ?>
      <div class="col-12"><label class="pc-label">Job Description</label><textarea name="description" class="form-control form-control-sm" rows="4"><?=clean($editData["description"]??"")?></textarea></div>
    </div>
    <div class="mt-3 d-flex gap-2"><button class="btn btn-pc">Save Job Opening</button><a href="?tab=jobs" class="btn btn-outline-secondary">Cancel</a></div>
  </form>
</div>

<?php elseif($tab==="candidates" && $selJob):
  $jobInfo = $db->fetchOne("SELECT * FROM job_openings WHERE id=?",[$selJob]);
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-user-plus me-2"></i>Add Candidate</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save_candidate"><input type="hidden" name="job_id" value="<?=$selJob?>">
        <div class="mb-2"><label class="pc-label">Name</label><input type="text" name="name" class="form-control form-control-sm" required></div>
        <div class="mb-2"><label class="pc-label">Email</label><input type="email" name="email" class="form-control form-control-sm"></div>
        <div class="mb-2"><label class="pc-label">Phone</label><input type="text" name="phone" class="form-control form-control-sm"></div>
        <div class="mb-2"><label class="pc-label">Experience (yrs)</label><input type="number" name="exp" class="form-control form-control-sm" min="0"></div>
        <div class="mb-2"><label class="pc-label">Current Company</label><input type="text" name="current_co" class="form-control form-control-sm"></div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">Current CTC (₹)</label><input type="number" name="current_ctc" class="form-control form-control-sm"></div>
          <div class="col"><label class="pc-label">Expected CTC (₹)</label><input type="number" name="expected_ctc" class="form-control form-control-sm"></div>
        </div>
        <div class="mb-3"><label class="pc-label">Source</label><select name="source" class="form-select form-select-sm"><option value="direct">Direct</option><option value="portal">Job Portal</option><option value="referral">Referral</option><option value="consultant">Consultant</option></select></div>
        <button class="btn btn-pc btn-sm w-100">Add Candidate</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><?=clean($jobInfo["title"])?> — <?=count($apps)?> Candidates</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Name</th><th>Contact</th><th>Experience</th><th>Current CTC</th><th>Expected</th><th>Stage</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach($apps as $a): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($a["candidate_name"])?></div><small class="text-muted"><?=clean($a["source"]??"")?></small></td>
            <td><div><?=clean($a["candidate_email"]??"")?></div><small><?=clean($a["candidate_phone"]??"")?></small></td>
            <td><?=$a["years_experience"]?> yrs</td>
            <td><?=$a["current_ctc"]?"₹".number_format($a["current_ctc"]):"—"?></td>
            <td><?=$a["expected_ctc"]?"₹".number_format($a["expected_ctc"]):"—"?></td>
            <td><?=statusBadge($a["status"])?></td>
            <td>
              <form method="POST" class="d-inline">
                <?=csrfField()?><input type="hidden" name="action" value="move_stage"><input type="hidden" name="id" value="<?=$a["id"]?>">
                <select name="stage" class="form-select form-select-sm d-inline" style="width:100px" onchange="this.form.submit()">
                  <?php foreach($stages as $s): ?><option value="<?=$s?>" <?=$a["status"]===$s?"selected":""?>><?=ucfirst($s)?></option><?php endforeach; ?>
                </select>
              </form>
            </td>
          </tr>
          <?php endforeach; if(!$apps): ?><tr><td colspan="7" class="text-center text-muted py-3">No candidates yet</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . "/../../includes/footer.php"; ?>