<?php
/*
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json");
*/

include '../connection.php';

// Set headers for JSON response
header("Content-Type: application/json");

$response = array();

// Check required fields
if (
    isset($_POST['fname']) && !empty($_POST['fname']) &&
    isset($_POST['lname']) && !empty($_POST['lname']) &&
    isset($_POST['conno']) && !empty($_POST['conno']) &&
    isset($_POST['email']) && !empty($_POST['email']) &&
    isset($_POST['pass']) && !empty($_POST['pass']) &&
    isset($_POST['designation']) && !empty($_POST['designation']) &&
    isset($_POST['join_date']) && !empty($_POST['join_date']) &&
    isset($_POST['birth_date']) && !empty($_POST['birth_date']) &&
    isset($_POST['usertype']) && !empty($_POST['usertype']) &&
    isset($_FILES['image'])
) {
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $conno = $_POST['conno'];
    $email = $_POST['email'];
    $pass = md5($_POST['pass']);
    $designation = $_POST['designation'];
    $join_date = $_POST['join_date'];
    $birth_date = $_POST['birth_date'];
    $usertype = $designation;
    $image = $_FILES['image'];
    $is_verified = 1;
    
    // Image Upload
    $target_dir = "../employee_images/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $image_name = uniqid("emp_") . "_" . basename($image["name"]);
    $target_file = $target_dir . $image_name;

    if (move_uploaded_file($image["tmp_name"], $target_file)) {
        // Insert into database
        $stmt = $conn->prepare("INSERT INTO tblcred (fname, lname, conno, email, pass, designation, join_date, birth_date, usertype, image, is_verified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssssi", $fname, $lname, $conno, $email, $pass, $designation, $join_date, $birth_date, $usertype, $image_name, $is_verified);

        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = "Employee added successfully";
        } else {
            $response['success'] = false;
            $response['message'] = "Failed to insert employee: " . $stmt->error;
        }

        $stmt->close();
    } else {
        $response['success'] = false;
        $response['message'] = "Failed to upload image";
    }

} else {
    $response['success'] = false;
    $response['message'] = "All fields are required";
}

echo json_encode($response);


?>
