<?php
header("Content-Type: application/json");
require("../includes/config.php");

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

// Check required fields (stream_id removed from logic)
if(empty($data['id']) || empty($data['class_id']) || empty($data['subject_name'])){
    echo json_encode(["status"=>"error","message"=>"All fields required"]);
    exit;
}

$id = (int)$data['id'];
$class_id = (int)$data['class_id'];
$subject_name = trim($data['subject_name']);

// Mark distribution values
$theory_max    = isset($data['theory_max']) ? (int)$data['theory_max'] : 0;
$practical_max = isset($data['practical_max']) ? (int)$data['practical_max'] : 0;
$pass_marks    = isset($data['pass_marks']) ? (int)$data['pass_marks'] : 33;

try {
    // Stream_id removed from SET clause
    $sql = "UPDATE subjects 
            SET class_id = ?, 
                subject_name = ?, 
                theory_max = ?, 
                practical_max = ?, 
                pass_marks = ? 
            WHERE id = ?";
            
    $stmt = $pdo->prepare($sql);
    
    // Execute with exactly 6 parameters
    $stmt->execute([
        $class_id, 
        $subject_name, 
        $theory_max, 
        $practical_max, 
        $pass_marks, 
        $id
    ]);

    echo json_encode(["status"=>"success","message"=>"Subject updated successfully"]);

} catch(PDOException $e){
    if ($e->getCode() == 23000) {
        echo json_encode(["status"=>"error","message"=>"This subject name already exists for this class"]);
    } else {
        echo json_encode(["status"=>"error","message"=>"Database error: " . $e->getMessage()]);
    }
}
?>