<?php
require_once('../config.php');
require_once('../mail/pip_mail.php');

if (isset($_POST['add_pip_submit'])) {
    $employee_id = $_POST['employee_id'];
    $until = $_POST['until'];

    // select employee from users using mysqli_query()
    $result = mysqli_query($db, "SELECT name, email FROM users WHERE employee_id = '$employee_id'");
    $row = mysqli_fetch_assoc($result);
    if(empty($row)) {
        echo json_encode(['status' => 404, 'message' => 'Employee not found']);
        exit();
    }

    $mail_status = pipMail([$row['email'], $row['name'], $until]);
    if($mail_status!=1){
        echo json_encode(['status' => 500, 'message' => 'Failed to send PIP email', 'error'=> $mail_status]);
        exit();
    }

    // insert in pips table using mysqli_query()
    $insert_query = "INSERT INTO pips (employee_id, until) VALUES ('$employee_id', '$until')";
    if (!mysqli_query($db, $insert_query)) {
        echo json_encode(['status' => 500, 'message' => 'Failed to insert PIP', 'error'=> mysqli_error($db)]);
        exit();
    }

    echo json_encode(['status' => 200, 'message' => 'PIP Send Successfully']);
    exit();
}
?>