<?php
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'HEAD_NURSE') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$conn = db_connect();

try {
    $nurse_id = isset($_POST['nurse_id']) ? intval($_POST['nurse_id']) : 0;
    $review_period = isset($_POST['review_period']) ? $_POST['review_period'] : '';
    $clinical_skills = isset($_POST['clinical_skills']) ? intval($_POST['clinical_skills']) : 0;
    $patient_care = isset($_POST['patient_care']) ? intval($_POST['patient_care']) : 0;
    $communication = isset($_POST['communication']) ? intval($_POST['communication']) : 0;
    $teamwork = isset($_POST['teamwork']) ? intval($_POST['teamwork']) : 0;
    $punctuality = isset($_POST['punctuality']) ? intval($_POST['punctuality']) : 0;
    $initiative = isset($_POST['initiative']) ? intval($_POST['initiative']) : 0;
    $strengths = isset($_POST['strengths']) ? trim($_POST['strengths']) : '';
    $improvements = isset($_POST['improvements']) ? trim($_POST['improvements']) : '';
    $comments = isset($_POST['comments']) ? trim($_POST['comments']) : '';
    
    // Validation
    if ($nurse_id <= 0 || empty($review_period) || empty($comments)) {
        throw new Exception('Missing required fields');
    }
    
    $scores = [$clinical_skills, $patient_care, $communication, $teamwork, $punctuality, $initiative];
    foreach ($scores as $score) {
        if ($score < 1 || $score > 10) {
            throw new Exception('All ratings must be between 1 and 10');
        }
    }
    
    $conn->begin_transaction();
    
    // Verify nurse exists
    $nurse_sql = "SELECT n.*, CONCAT(u.first_name, ' ', u.last_name) as nurse_name
                  FROM nurses n
                  INNER JOIN users u ON n.user_id = u.user_id
                  WHERE n.nurse_id = ?";
    $stmt = $conn->prepare($nurse_sql);
    $stmt->bind_param('i', $nurse_id);
    $stmt->execute();
    $nurse = $stmt->get_result()->fetch_assoc();
    
    if (!$nurse) {
        throw new Exception('Nurse not found');
    }
    
    // Calculate overall score
    $overall_score = round(($clinical_skills + $patient_care + $communication + 
                           $teamwork + $punctuality + $initiative) / 6, 2);
    
    // Log the performance review in activity log
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'PERFORMANCE_REVIEW', 'NURSING', ?, 'REVIEW', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $user_id = $_SESSION['user_id'];
    $review_data = json_encode([
        'nurse_id' => $nurse_id,
        'nurse_name' => $nurse['nurse_name'],
        'review_period' => $review_period,
        'review_date' => date('Y-m-d'),
        'scores' => [
            'clinical_skills' => $clinical_skills,
            'patient_care' => $patient_care,
            'communication' => $communication,
            'teamwork' => $teamwork,
            'punctuality' => $punctuality,
            'initiative' => $initiative,
            'overall' => $overall_score
        ],
        'strengths' => $strengths,
        'improvements' => $improvements,
        'comments' => $comments,
        'reviewed_by' => $_SESSION['user_name']
    ]);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt->bind_param('iisss', $user_id, $nurse_id, $review_data, $ip, $user_agent);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to save performance review');
    }
    
    $review_id = $stmt->insert_id;
    
    // In production, insert into performance_reviews table:
    /*
    $review_sql = "INSERT INTO performance_reviews (
                      nurse_id, review_period, review_date,
                      clinical_skills, patient_care, communication, teamwork, punctuality, initiative,
                      overall_score, strengths, improvements, comments, reviewed_by
                   ) VALUES (?, ?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    */
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Performance review submitted successfully',
        'review_id' => $review_id,
        'overall_score' => $overall_score
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>