<?php
if (isset($_POST['behavioral_upload_btn'])) {
    $total_num = (int)$_POST["total_num"];

    if ($total_num > 0) {
        // Use the first entry to check for duplicate record
        $student_class = $_POST['student_class'][0];
        $behavioral_term = $_POST['behavioral_term'][0];
        $behavioral_session = $_POST['behavioral_session'][0];

        // Check for existing behavioral record
        $check_stmt = $connection->prepare("SELECT id FROM behavioral WHERE class = ? AND term = ? AND session = ?");
        $check_stmt->bind_param("sss", $student_class, $behavioral_term, $behavioral_session);
        $check_stmt->execute();
        $check_stmt->store_result();

        if ($check_stmt->num_rows > 0) {
            $_SESSION['msg'] = "❌ This Behavioral Record Has Already Been Uploaded";
            $_SESSION['type'] = "warning";
        } else {
            // Prepare insert statement
            $insert_stmt = $connection->prepare("
                INSERT INTO behavioral (
                    reg_number, name, class, term, session, puntuality, neatness,
                    relationship_with_others, regards_for_authority, attitude_towards_academics,
                    honesty, initiative, form_master_or_mistress, date
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            if (!$insert_stmt) {
                $_SESSION['msg'] = "❌ Failed to prepare insert statement.";
                $_SESSION['type'] = "error";
                header("Location: student_conducts");
                exit();
            }

            $date = date('d/M/Y');
            $success = true;

            for ($j = 0; $j < $total_num; $j++) {
                $reg_no = $_POST['student_reg_no'][$j];
                $name = $_POST['student_name'][$j];
                $class = $_POST['student_class'][$j];
                $term = $_POST['behavioral_term'][$j];
                $session = $_POST['behavioral_session'][$j];
                $puntuality = $_POST['puntuality'][$j];
                $neatness = $_POST['neatness'][$j];
                $relationship = $_POST['relationship_with_others'][$j];
                $authority = $_POST['regards_for_authority'][$j];
                $attitude = $_POST['attitude_towards_academics'][$j];
                $honesty = $_POST['honesty'][$j];
                $initiative = $_POST['initiative'][$j];
                $form_teacher = $_POST['form_master_or_mistress'][$j];

                $insert_stmt->bind_param(
                    "ssssssssssssss",
                    $reg_no, $name, $class, $term, $session,
                    $puntuality, $neatness, $relationship, $authority,
                    $attitude, $honesty, $initiative, $form_teacher, $date
                );

                if (!$insert_stmt->execute()) {
                    $success = false;
                    break;
                }
            }

            $insert_stmt->close();

            if ($success) {
                $_SESSION['msg'] = "✅ Behavioral upload successful.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "❌ Failed during upload. Some records may be incomplete.";
                $_SESSION['type'] = "error";
            }
        }

        $check_stmt->close();
    } else {
        $_SESSION['msg'] = "❌ No student data submitted.";
        $_SESSION['type'] = "warning";
    }

    header("Location: student_conducts");
    exit();
}
?>

<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Behavioral Analysis</h1>
    <p>Manual Upload</p>
  </div>
</div>

<div class="card">
    <div class = 'row'>
        <div class = 'col-xs-12 col-sm-12 col-md-12'>
            <div class = 'panel panel-primary ch'>
                <div class = 'panel-heading'>
                    <h4 class = 'text-center'>Manually Save Students Behavioral Analysis</h4>
                </div><br/>
                <div class = 'panel-body'>
                    <form method='POST' action=''>
                        <div class='row'>
                            <div class = 'col-xs-12 col-sm-12 col-md-4'>
                                <div class = 'input-group'>
                                    <span class = 'input-group-addon' id = 'sizing-addon2'>CLASS</span>
                                    <select class='form-control' name='class' required>
                                        <option selected ><?php echo $select; ?></option>
                                        <?php
                                            $query = " SELECT * FROM `classes` ";
                                            $run_query = mysqli_query($connection, $query);
                                            if(mysqli_num_rows($run_query) > 0){
                                                while($result = mysqli_fetch_assoc($run_query)){
                                                    $attendance = $result['classes'];
                                                    echo"
                                                        <option>{$attendance}</option>
                                                    ";
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class = 'col-xs-12 col-sm-12 col-md-4'>
                                <div class = 'input-group'>
                                    <span class = 'input-group-addon' id = 'sizing-addon2'>TERM:</span>
                                    <select class='form-control' name='term' required>
                                        <option selected ><?php echo $select; ?></option>
                                        <?php
                                            $term_array = array("First Term", "Second Term", "Third Term");

                                            foreach($term_array as $term){
                                                echo "<option>{$term}</option><br>";
                                            }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class = 'col-xs-12 col-sm-12 col-md-4'>
                                <div class = 'input-group'>
                                    <span class = 'input-group-addon' id = 'sizing-addon2'>SESSION</span>
                                    <select class='form-control' name='session' required>
                                        <?php
                                            ///////////// POST ACTION TO DISPLAY CURRENT SESSION //////////////
                                            $query = " SELECT * FROM `current_season` ";
                                            $run_query = mysqli_query($connection, $query);
                                            if(mysqli_num_rows($run_query) == 1){
                                                while($result = mysqli_fetch_assoc($run_query)){
                                                    $show_current_session = $result['current_session'];
                                                    echo"
                                                        <option>{$show_current_session}</option>
                                                    ";
                                                }
                                            }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div><br>
                        <div class='row'>
                            <div class = 'col-xs-12 col-sm-12 col-md-4'>
                                <button type = 'submit' name='behavioral_get_student_btn' class ='btn btn-primary btn-md'><span class = 'glyphicon glyphicon-user'></span>&nbsp; SHOW STUDENTS</button><br/> 
                            </div>
                        </div>
                    </form>
                </div>
        </div>
    </div>
	<?php
	if (isset($_POST['behavioral_get_student_btn'])) {
		$class = $_POST['class'];
		$term = inject_checker($connection, $_POST['term']);
		$session = inject_checker($connection, $_POST['session']);
		$select = "--select--"; // assumed from your previous context

		if ($class === $select) {
		    $_SESSION['msg'] = "Please select a valid class for result upload.";
		    $_SESSION['type'] = "warning";
		    header("Location: student_conducts"); exit();
		} elseif ($term === $select) {
		    $_SESSION['msg'] = "Please select a valid term for result upload.";
		    $_SESSION['type'] = "warning";
		    header("Location: student_conducts"); exit();
		} else {
		    // Use prepared statement
		    $stmt = $connection->prepare("SELECT firstname, othername, lastname, reg_number FROM students WHERE class = ? AND status = 'active' ");
		    $stmt->bind_param("s", $class);
		    $stmt->execute();
		    $result = $stmt->get_result();

		    if ($result->num_rows > 0) {
		        echo "
		            <div class='row text-center'>
		                <div class='col-md-12'>
		                    <h5 style='margin-top: 0;'>{$school_name}</h5>
		                    <h5>Behavioral Analysis</h5>
		                </div>
		                <div class='col-md-4'>
		                    <p><b>CLASS: </b>{$class}</p>
		                </div> 
		                <div class='col-md-4'>
		                    <p><b>TERM: </b>{$term}</p>
		                </div>
		                <div class='col-md-4'>
		                    <p><b>SESSION: </b>{$session}</p>
		                </div>
		            </div>
		            <form method='POST' action=''>
		        ";

		        $i = 0;
		        $k = 1;
		        echo "<div class='row'>";

		        while ($row = $result->fetch_assoc()) {
		            $fname = $row['firstname'];
		            $oname = $row['othername'];
		            $lname = $row['lastname'];
		            $reg_no = $row['reg_number'];

		            $full_name = "$fname $oname $lname";

		            // Abbreviate if 3 names and total length > 25
		            $name_parts = explode(" ", $full_name);
		            if (count($name_parts) === 3 && strlen($full_name) > 25) {
		                $full_name = "{$name_parts[0]} {$name_parts[1][0]}. {$name_parts[2]}";
		            }

		            echo "
		                <div class='col-md-4 mb-5'>
		                    <div class='card p-3'>
		                        <h5>{$k}. {$full_name}</h5>
		                        <input type='hidden' name='student_name[]' value='{$full_name}' class='form-control' readonly />
		                        <input type='hidden' name='student_reg_no[]' value='{$reg_no}' />
		                        <input type='hidden' name='student_class[]' value='{$class}' />
		                        <input type='hidden' name='behavioral_term[]' value='{$term}' />
		                        <input type='hidden' name='behavioral_session[]' value='{$session}' />

		                        <select name='puntuality[]' class='form-control mb-2' required>
		                            <option disabled selected>Punctuality</option>" . options() . "
		                        </select>

		                        <select name='neatness[]' class='form-control mb-2' required>
		                            <option disabled selected>Neatness</option>" . options() . "
		                        </select>

		                        <select name='relationship_with_others[]' class='form-control mb-2' required>
		                            <option disabled selected>Relationship With Others</option>" . options() . "
		                        </select>

		                        <select name='regards_for_authority[]' class='form-control mb-2' required>
		                            <option disabled selected>Regards for Authority</option>" . options() . "
		                        </select>

		                        <select name='attitude_towards_academics[]' class='form-control mb-2' required>
		                            <option disabled selected>Attitude Towards Academics</option>" . options() . "
		                        </select>

		                        <select name='honesty[]' class='form-control mb-2' required>
		                            <option disabled selected>Honesty</option>" . options() . "
		                        </select>

		                        <select name='initiative[]' class='form-control mb-2' required>
		                            <option disabled selected>Initiative</option>" . options() . "
		                        </select>

		                        <select name='form_master_or_mistress[]' class='form-control' required>
		                            <option disabled selected>Form Master/Mistress</option>" . options() . "
		                        </select>
		                    </div>
		                </div>
		            ";
		            $i++;
		            $k++;
		        }

		        echo "</div>"; // End grid

		        echo "
		            <div class='row mt-4'>
		                <div class='col-md-3'>
		                    <input type='hidden' name='total_num' value='{$i}' />
		                    <input type='submit' name='behavioral_upload_btn' value='Upload' class='btn btn-primary' />
		                    <button type='button' class='btn btn-default' onclick='window.print()'><span class='glyphicon glyphicon-print'></span> Print</button>
		                </div>
		            </div>
		            </form>
		        ";
		    } else {
		        echo "<p class='text-danger'><b>No student records found for this class.</b></p>";
		    }

		    $stmt->close();
		}
	}

	/**
	 * Utility function for select options
	 */
	function options() {
		return "<option>1</option><option>2</option><option>3</option><option>4</option><option>5</option>";
	}
	?>
</div>
