<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
require_once('../config.php');


if (isset($_POST['referral_form_submit'])) {
    // {
    //     "job_name": "B2C Executive - Part Time (Sales to B2C Clients)",
    //     "app_status": "Applied",
    //     "j_id": "1226",
    //     "referred_by": "REFER_SHIVAM_SINGHAL_NI171",
    //     "applicant_email": "shivamsinghal160@gmail.com",
    //     "referral_form_submit": "true"
    // }
    $job_name = mysqli_real_escape_string($db, $_POST['job_name']);
    $j_id = mysqli_real_escape_string($db, $_POST['j_id']);
    $app_status = mysqli_real_escape_string($db, $_POST['app_status']);
    $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);

    $emp_id = end(explode('_', $_POST['referred_by']));
    $emp_id = mysqli_real_escape_string($db, $emp_id);


    $exist_result = mysqli_query($db, "SELECT * FROM refer_earn WHERE employee_id = '$emp_id' AND j_id = '$j_id' AND applicant_email = '$applicant_email'");
    if( mysqli_num_rows($exist_result) > 0) {
        echo json_encode(array('status' => 400, 'message' => 'Referral already exists for this applicant.'));
        exit;
    }
    
    $q = mysqli_query($db, "INSERT INTO refer_earn (employee_id, job_name, j_id, app_status, applicant_email) VALUES ('$emp_id', '$job_name', '$j_id', '$app_status', '$applicant_email')");
    if (!$q) {
        echo json_encode(array('status' => 500, 'message' => 'Database Error', 'error' => mysqli_error($db)));
        exit;
    }
    echo json_encode(array('status' => 200, 'message' => 'Form Submitted Successfully!!!'));
}


if(isset($_POST['referral_applicant_status_update'])) {
    // {
    //     "referral_applicant_status_update": "true",
    //     "applicant_email": "shivamsinghal160@gmail.com",
    //     "j_id": "1226",
    //     "app_status": "Hired",
    //     "referred_by": "REFER_SHIVAM_SINGHAL_NI171"
    // }
    $applicant_email = mysqli_real_escape_string($db, $_POST['applicant_email']);
    $j_id = mysqli_real_escape_string($db, $_POST['j_id']);
    $app_status = mysqli_real_escape_string($db, $_POST['app_status']);

    $emp_id = end(explode('_', $_POST['referred_by']));
    $emp_id = mysqli_real_escape_string($db, $emp_id);

    $query = "UPDATE refer_earn SET app_status = '$app_status' WHERE employee_id = '$emp_id' AND j_id = '$j_id' AND applicant_email = '$applicant_email'";
    $result = mysqli_query($db, $query);

    if ($result) {
        echo json_encode(array('status' => 200, 'message' => 'Status Updated Successfully'));
    } else {
        echo json_encode(array('status' => 500, 'message' => 'Database Error', 'error' => mysqli_error($db)));
    }
}
