<?php 
include "../../db.php";
session_start();

if (isset($_POST['start'])) {
    $start= mysqli_real_escape_string($con,$_POST['start']);
    $AndWhere ='';

    if (!empty($_POST['FirstFilterValue'])) {
        $AndWhere = "AND ad_title = '$_POST[FirstFilterValue]'";
    }

    $sql = "SELECT * FROM ad WHERE ad_uploadedby = '$_SESSION[uref]' AND ad_display ='disabled' $AndWhere ORDER BY ad_id DESC LIMIT $start,10";

    $res = mysqli_query($con,$sql);
    if ($total_rows=mysqli_num_rows($res)>0) {
        $s_output='';
        $c = $start+1;
        while ($rows=mysqli_fetch_assoc($res)) {

            $class_ids = $rows['ad_class'];
            $class_sql = mysqli_query($con, "SELECT sclass FROM class WHERE sid IN ($class_ids)");

            $class_names = [];
            while($class_row = mysqli_fetch_assoc($class_sql)){
                $class_names[] = $class_row['sclass'];
            }

            $class_names_string = implode(', ', $class_names);

            $locations = $rows["ad_location"];
            // Extract state-district pairs
            $pairs = explode(',', $locations);

            // Group district IDs by state IDs
            $state_district_map = [];
            foreach ($pairs as $pair) {
                list($state_id, $district_id) = explode('-', $pair);
                if (!isset($state_district_map[$state_id])) {
                    $state_district_map[$state_id] = [];
                }
                if ($district_id != '0') {
                    $state_district_map[$state_id][] = $district_id;
                }
            }
                    
            // Query to get state names
            $state_ids = array_keys($state_district_map);
            $state_ids_str = implode(',', $state_ids);
            $state_sql = "SELECT id, name FROM state WHERE id IN ($state_ids_str)";
            $state_res = mysqli_query($con, $state_sql);

            $states = [];
            while ($row = mysqli_fetch_assoc($state_res)) {
                $states[$row['id']] = $row['name'];
            }

            // Query to get district names
            $all_district_ids = array_merge(...array_values($state_district_map));
            if (count($all_district_ids) > 0) {
                $district_ids_str = implode(',', $all_district_ids);
                $district_sql = "SELECT id, distName, stateId FROM dist WHERE id IN ($district_ids_str)";
                $district_res = mysqli_query($con, $district_sql);

                $districts = [];
                while ($row = mysqli_fetch_assoc($district_res)) {
                    $districts[$row['stateId']][$row['id']] = $row['distName'];
                }
            } else {
                $districts = [];
            }
            ?>
<li class='clearfix' style='float: none;'>
    <div class="single-dis mb-2">
        <div class='row align-items-center'>
            <div class='col-md-6 col-9 mb-3 text-white'>
                <b>Ad Title : </b> <?php echo $rows["ad_title"];?> <br>
                <b>Ad for Class : </b> <?php echo $class_names_string;?>
                <p class="m-0"><strong>AD Locations :-</strong></p>
                <?php
                // Format the output
                foreach ($state_district_map as $state_id => $district_ids) {
                    ?>
                <p class="m-0"><strong>State:</strong> <?php echo $states[$state_id]; ?> </p>
                <?php
                    if (!empty($district_ids)) {
                        ?>
                <ul class="d-flex">
                    <?php
                        foreach ($district_ids as $district_id) {
                            ?>
                    <li style="margin:0px 30px 0px 0px;"><?php echo $districts[$state_id][$district_id]; ?></li>
                    <?php
                        }
                        ?>
                </ul>
                <?php
                    } else {
                        ?>
                <em>All districts selected.</em><br>
                <?php
                    }
                }
                ?>

            </div>
            <div class="col-md-4 mb-3">
                <img src="../../upload/ad/<?php echo $rows["ad_img"];?>" class="img-fluid"
                    alt="<?php echo $rows["ad_title"];?>">
            </div>
            <div class='col-md-2 col-12 text-end'>
                <a href='view-ad.php?edit_id=<?php echo $rows["ad_id"];?>' class='btn btn-success'
                    title='Click to Edit'><i class='fa fa-edit' aria-hidden='true'></i> </a>
                <a href='view-ad.php?del_id=<?php echo $rows["ad_id"];?>' class='btn btn-warning'
                    title='Click to Restore'><i class='fa fa-recycle' aria-hidden='true'></i> </a>
            </div>
        </div>
    </div>
</li>
<?php
$c++;
}
mysqli_close($con);
// echo $s_output;
}
}
?>