<?php
session_start();
include 'config.php';

// Ensure only Admins and Super Admins can save performance data
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'Super Admin' && $_SESSION['role'] != 'Admin')) {
    echo json_encode(["success" => false, "message" => "Unauthorized access"]);
    exit();
}

// Get the JSON input
$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data['performance'])) {
    echo json_encode(["success" => false, "message" => "Invalid input"]);
    exit();
}

$performance = $data['performance'];

// Validate input
if (count($performance) < 9) {
    echo json_encode(["success" => false, "message" => "Incomplete data"]);
    exit();
}

$username = $performance[0];
$department = $performance[1];
$kpa = $performance[2];
$kra = $performance[3];
$kpi = $performance[4];
$weight = $performance[5];
$periodicity = $performance[6];
$measuring = $performance[7];
$comments = $performance[8];

// Fetch employee ID
$user_query = $conn->prepare("SELECT id FROM users WHERE username = ? AND department = ?");
$user_query->bind_param("ss", $username, $department);
$user_query->execute();
$user_result = $user_query->get_result();

if ($user_result->num_rows == 0) {
    echo json_encode(["success" => false, "message" => "User not found"]);
    exit();
}

$user = $user_result->fetch_assoc();
$employee_id = $user['id'];

// Insert into performance_metrics table
$metric_query = $conn->prepare("INSERT INTO performance_metrics (kpa, kra, kpi, weight, periodicity, measuring, comments) VALUES (?, ?, ?, ?, ?, ?, ?)");
$metric_query->bind_param("sssssss", $kpa, $kra, $kpi, $weight, $periodicity, $measuring, $comments);

if (!$metric_query->execute()) {
    echo json_encode(["success" => false, "message" => "Error saving metrics"]);
    exit();
}

$metric_id = $conn->insert_id;

// Insert into employee_performance table
$performance_query = $conn->prepare("INSERT INTO employee_performance (employee_id, metric_id) VALUES (?, ?)");
$performance_query->bind_param("ii", $employee_id, $metric_id);

if ($performance_query->execute()) {
    echo json_encode(["success" => true, "message" => "Performance data saved successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Error saving performance"]);
}

$conn->close();
?>
