<?php

require_once '../../../config.php';

$conn = getDBConnection();



error_reporting(E_ALL);

ini_set('display_errors', 0);

ini_set('log_errors', 1);



$response = ['success' => false, 'message' => ''];



// Check if we have POST data

if (empty($_POST)) {

    $response['message'] = 'No data received';

    echo json_encode($response);

    exit;

}



$class_name = $_POST['class_name'] ?? '';

$subject_type = $_POST['subject_type'] ?? 'existing';

$subject_id = null;



// Handle subject

if ($subject_type === 'new') {

    // Create new subject first

    $new_subject_name = trim($_POST['new_subject_name'] ?? '');

    $new_subject_code = trim($_POST['new_subject_code'] ?? '');

    

    if (empty($new_subject_name) || empty($new_subject_code)) {

        $response['message'] = 'Subject name and code are required for new subject';

        echo json_encode($response);

        exit;

    }

    

    // Check if subject already exists

    $check_stmt = $conn->prepare("SELECT id FROM subjects WHERE subject_name = ? OR subject_code = ?");

    $check_stmt->bind_param("ss", $new_subject_name, $new_subject_code);

    $check_stmt->execute();

    $check_result = $check_stmt->get_result();

    

    if ($check_result->num_rows > 0) {

        // Subject exists, use it

        $row = $check_result->fetch_assoc();

        $subject_id = $row['id'];

    } else {

        // Insert new subject

        $insert_stmt = $conn->prepare("INSERT INTO subjects (subject_name, subject_code, active) VALUES (?, ?, 'yes')");

        $insert_stmt->bind_param("ss", $new_subject_name, $new_subject_code);

        

        if ($insert_stmt->execute()) {

            $subject_id = $insert_stmt->insert_id;

        } else {

            $response['message'] = 'Failed to create new subject: ' . $insert_stmt->error;

            echo json_encode($response);

            exit;

        }

        $insert_stmt->close();

    }

    $check_stmt->close();

} else {

    // Use existing subject

    $subject_id = intval($_POST['subject_id'] ?? 0);

    

    if (!$subject_id) {

        $response['message'] = 'Please select a subject';

        echo json_encode($response);

        exit;

    }

}



// Get scoring configuration

$class_score_percent = intval($_POST['class_score_percent'] ?? 50);

$exam_score_percent = intval($_POST['exam_score_percent'] ?? 50);

$max_class_score = floatval($_POST['max_class_score'] ?? 50);

$max_exam_score = floatval($_POST['max_exam_score'] ?? 50);

$is_compulsory = isset($_POST['is_compulsory']) ? 'yes' : 'no';

$display_order = intval($_POST['display_order'] ?? 0);



// Validate class name

if (empty($class_name)) {

    $response['message'] = 'Class name is required';

    echo json_encode($response);

    exit;

}



// Validate percentages sum to 100

if ($class_score_percent + $exam_score_percent != 100) {

    $response['message'] = 'Class Score % and Exam Score % must add up to 100%';

    echo json_encode($response);

    exit;

}



// Begin transaction

$conn->begin_transaction();



try {

    // Check if subject already exists for this class

    $check_stmt = $conn->prepare("SELECT id FROM class_subjects WHERE class_name = ? AND subject_id = ?");

    $check_stmt->bind_param("si", $class_name, $subject_id);

    $check_stmt->execute();

    $check_result = $check_stmt->get_result();

    $exists = $check_result->num_rows > 0;

    $check_stmt->close();



    if ($exists) {

        // Update existing

        $stmt = $conn->prepare("

            UPDATE class_subjects 

            SET class_score_percent = ?, exam_score_percent = ?,

                max_class_score = ?, max_exam_score = ?,

                is_compulsory = ?, display_order = ?

            WHERE class_name = ? AND subject_id = ?

        ");

        

        $stmt->bind_param(

            "iiddissi",

            $class_score_percent,

            $exam_score_percent,

            $max_class_score,

            $max_exam_score,

            $is_compulsory,

            $display_order,

            $class_name,

            $subject_id

        );

    } else {

        // Insert new

        $stmt = $conn->prepare("

            INSERT INTO class_subjects (

                class_name, subject_id, class_score_percent, exam_score_percent,

                max_class_score, max_exam_score, is_compulsory, display_order

            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)

        ");

        

        $stmt->bind_param(

            "siiiddis",

            $class_name,

            $subject_id,

            $class_score_percent,

            $exam_score_percent,

            $max_class_score,

            $max_exam_score,

            $is_compulsory,

            $display_order

        );

    }



    if (!$stmt->execute()) {

        throw new Exception($stmt->error);

    }

    

    $conn->commit();

    

    // Get the subject name for response

    $subject_name = '';

    if ($subject_type === 'new') {

        $subject_name = $new_subject_name;

    } else {

        $name_stmt = $conn->prepare("SELECT subject_name FROM subjects WHERE id = ?");

        $name_stmt->bind_param("i", $subject_id);

        $name_stmt->execute();

        $name_result = $name_stmt->get_result();

        if ($name_row = $name_result->fetch_assoc()) {

            $subject_name = $name_row['subject_name'];

        }

        $name_stmt->close();

    }

    

    $response['success'] = true;

    $response['message'] = 'Subject saved successfully';

    $response['subject_name'] = $subject_name;

    $response['subject_id'] = $subject_id;

    $response['is_new'] = ($subject_type === 'new');

    

} catch (Exception $e) {

    $conn->rollback();

    $response['message'] = 'Database error: ' . $e->getMessage();

    error_log("save_class_subject.php - Error: " . $e->getMessage());

}



$conn->close();

echo json_encode($response);