<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include '../../../config/index.php';
$data = array();
$students = array();

$sql = "SELECT * FROM ParentStudents WHERE parent_id='" . $_GET["parent_id"] . "' ";

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $sql_stdnt = "SELECT * FROM students WHERE ParentStudents_id='" . $row["ParentStudents_id"] . "' AND student_id='" . $row["student_id"] . "'";
        // echo  $sql_stdnt;
        $result_stdnt = mysqli_query($conn, $sql_stdnt);
        if (mysqli_num_rows($result_stdnt) > 0) {
            while ($row_stdnt = mysqli_fetch_assoc($result_stdnt)) {
                $LearnerCreditsWallet_id = 0;
                $Percentage = 0;
                $Credits = 0;
                $Status = 0;
                $Used = 0;
                $Available = 0;

                $sql_lcw = "SELECT * FROM LearnerCreditsWallet WHERE student_id='" . $row_stdnt["student_id"] . "' ORDER BY dated DESC LIMIT 1";

                $result_lcw = mysqli_query($conn, $sql_lcw);
                if (mysqli_num_rows($result_lcw) > 0) {
                    while ($row_lcw = mysqli_fetch_assoc($result_lcw)) {

                        $Percentage = (((int)$row_lcw["Credits"] - (int)$row_lcw["Available"])) / ((int)$row_lcw["Credits"]) * 100;
                        $LearnerCreditsWallet_id = 0;
                        $Credits =  $row_lcw["Credits"];
                        $Status = $row_lcw["Status"];
                        $Used = $row_lcw["Used"];
                        $Available = $row_lcw["Available"];
                    }
                }
                if (!in_array($row_stdnt["student_id"], $students)) {
                    $curl_post_data = array(
                        'parent_id' => $_GET["parent_id"],
                        'student_id' => $row_stdnt["student_id"],
                        'LearnerCreditsWallet_id' => $LearnerCreditsWallet_id,
                        'Credits' => $Credits,
                        'Status' => $Status,
                        'Used' => $Used,
                        'Available' => $Available,
                        'Percentage' => $Percentage,
                        'learner_name' => $row_stdnt["learner_name"],
                        'learner_last_name' => $row_stdnt["learner_last_name"],
                        'learner_gender' => $row_stdnt["learner_gender"],
                        'learner_age' => $row_stdnt["learner_age"],
                        'learner_image' => $row_stdnt["learner_image"],

                    );
                    array_push($data, $curl_post_data);
                    array_push($students, $row_stdnt["student_id"]);
                }
            }
        }
    }
}
echo json_encode($data);
