<?php
// check_subject_code.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['exists' => false]);
    exit;
}

$subjectcode = trim($_POST['subjectcode'] ?? '');
$program_id = isset($_POST['program_id']) ? (int)$_POST['program_id'] : 0;
$college_id = isset($_POST['college_id']) ? (int)$_POST['college_id'] : 0;
$section_id = isset($_POST['section_id']) ? (int)$_POST['section_id'] : 0;

if (empty($subjectcode) || !$program_id || !$college_id || !$section_id) {
    echo json_encode(['exists' => false]);
    exit;
}

$stmt = $mysqli1->prepare("
    SELECT id FROM subjects 
    WHERE subjectcode = ? 
    AND program_id = ? 
    AND college_id = ? 
    AND section_id = ?
    AND deleted_at IS NULL
    LIMIT 1
");

$stmt->bind_param('siii', $subjectcode, $program_id, $college_id, $section_id);
$stmt->execute();
$stmt->store_result();

$exists = $stmt->num_rows > 0;
$stmt->close();

echo json_encode(['exists' => $exists]);
?>