<?php
session_start();
include('../include/connection.php');
//pagination
$pagination = "";
$sql="select * from scheduled_mails";

$text = "";

$conditions = array();
$fields=array();

if(isset($_GET['searchkey']) && $_GET['searchkey'] !="") {
    $conditions[] = "email_subject like :searchkey OR template_type like :searchkey OR participant_type like :searchkey";
    $keyword = '%'.$_GET['searchkey'].'%';
    $fields[':searchkey'] = $keyword;
}

if (count($conditions) > 0) {
    $sql .= " WHERE " . implode(' AND ', $conditions);
}

$r=$con->select_query($sql,$fields);
$sn=1;

$number_of_results = count($r);

$number_of_pages = ceil($number_of_results/$_GET['no_records']);
$page = $_GET['page'];
$start_from = ($page - 1) * $_GET['no_records'];

$sql .= " order by id DESC LIMIT ".$start_from.','.$_GET['no_records'];
$r=$con->select_query($sql,$fields);
$sn=$_GET['lastrecord'];
if($page == 1)
    $sn = 1;
    $today = date('d-m');
    $admin_count = 0;
    foreach($r as $value)
    {
      
        $star_mark = "";
        
        // if($value['email'])
        // {
        //     $star_mark = ' <i class="ft-user-check text-danger"></i>';
            $admin_count += 1;
        // }
            // interpret participant data for display
            $participant_display = '';
            $ptype = isset($value['participant_type']) ? $value['participant_type'] : 'all';
            $pdata = isset($value['participant_data']) ? $value['participant_data'] : '';
            if($ptype === 'all' || !$ptype) {
                $participant_display = 'All Staff';
            } else {
                $data = json_decode($pdata, true);
                if(!$data) $data = array();
                switch($ptype) {
                    case 'individual':
                        $ids = isset($data['individuals']) ? (array)$data['individuals'] : array();
                        if(empty($ids)) {
                            $participant_display = 'No individuals selected';
                        } else {
                            // fetch names
                            $placeholders = implode(',', array_fill(0, count($ids), '?'));
                            $sqln = "SELECT firstname, lastname FROM staff WHERE id IN ($placeholders)";
                            $names = array();
                            $rows = $con->select_query($sqln, $ids);
                            foreach($rows as $r) {
                                $names[] = trim($r['firstname'] . ' ' . $r['lastname']);
                            }
                            $participant_display = htmlspecialchars(implode(', ', $names));
                        }
                        break;
                    case 'department':
                        $depts = isset($data['departments']) ? (array)$data['departments'] : array();
                        $participant_display = !empty($depts) ? htmlspecialchars(implode(', ', $depts)) : 'No departments selected';
                        break;
                    case 'position':
                        $positions = isset($data['positions']) ? (array)$data['positions'] : array();
                        $participant_display = !empty($positions) ? htmlspecialchars(implode(', ', $positions)) : 'No positions selected';
                        break;
                    case 'dob':
                        $start = isset($data['dob_start']) ? $data['dob_start'] : '';
                        $end = isset($data['dob_end']) ? $data['dob_end'] : '';
                        if($start && $end) {
                            $participant_display = 'DOB: ' . date('d M, Y', strtotime($start)) . ' to ' . date('d M, Y', strtotime($end));
                        } elseif($start) {
                            $participant_display = 'DOB from: ' . date('d M, Y', strtotime($start));
                        } elseif($end) {
                            $participant_display = 'DOB until: ' . date('d M, Y', strtotime($end));
                        } else {
                            $participant_display = 'No DOB range selected';
                        }
                        break;
                    default:
                        $participant_display = htmlspecialchars($pdata);
                }
            }

            $text .= '<tr>' .
                '<td style="font-size:12px;">'.$sn.'</td>' .
                '<td>' . ucwords($value['template_type']) . ' Message</td>' .
                '<td>' . ucwords($value['email_subject']) . '</td>' .
                '<td>' . $participant_display . '</td>' .
                '<td>' . date('D M, Y', strtotime($value['created_at'])) . '</td>' .
                '<td>' . ($value['sent_status'] == 1 ? "Sent" : "Not Sent") . '</td>' .
            '</tr>';
            $sn++;
    }
    
    $prev = $page > 1 ? $page - 1 : $page;
    $next = $page + 1;
    $pagination = '<ul class="pagination pull-right">
                   <li class="footable-page-arrow"><a data-page="first" href="javascript:;" onclick="loadArticles(0, 1)"><span class="fa fa-angle-double-left"></span></a></li>
                   <li class="footable-page-arrow"><a data-page="prev" href="javascript:;" onclick="loadArticles(0, '.$prev.')"><span class="fa fa-angle-left"></span></a></li>';
    for($i=1; $i<=$number_of_pages; $i++)
    {
        $active = "";
        if($i == $page)
        {
            $active = "active";
        }
        $pagination .= '<li class="footable-page '.$active.'" onclick="loadArticles(0, '.$i.')"><a data-page="0" href="javascript:;">'.$i.'</a></li>';
    }
    
    
    $pagination .= '<li class="footable-page-arrow"><a data-page="next" href="javascript:;" onclick="loadArticles(0, '.$next.')"><span class="fa fa-angle-right"></span></a></li>
      <li class="footable-page-arrow"><a data-page="last" href="javascript:;" onclick="loadArticles(0, '.$number_of_pages.')"><span class="fa fa-angle-double-right"></span></a></li>
  </ul>';
    echo json_encode(array('text'=>$text, "pagination"=>$pagination, 'lastrecord'=>$sn, 'admin_count'=>$admin_count));
    ?>