<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    header('Location: index.php');

    exit;

}



// Role-based access control

$allowed_roles = ['admin', 'accountant', 'cashier', 'headteacher'];



if (!in_array($_SESSION['role'], $allowed_roles)) {

    header('Location: dashboard.php?error=access_denied');

    exit;

}



require_once 'config.php';

$conn = getDBConnection();



// ============ HELPER FUNCTIONS (DEFINED FIRST) ============



/**

 * Get setting value from database

 */

function getSetting($key, $default = '') {

    global $conn;

    $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");

    if (!$stmt) return $default;

    $stmt->bind_param('s', $key);

    $stmt->execute();

    $row = $stmt->get_result()->fetch_assoc();

    $stmt->close();

    return $row ? $row['setting_value'] : $default;

}



/**

 * Get class fee data

 */

function getClassFeeData($conn, $className) {

    $query = "SELECT * FROM fee_structures WHERE class_name = ? LIMIT 1";

    $stmt = $conn->prepare($query);

    $stmt->bind_param("s", $className);

    $stmt->execute();

    $result = $stmt->get_result();

    $data = $result->fetch_assoc();

    $stmt->close();

    

    return $data ?: null;

}



/**

 * Get upcoming fees for a class

 */

function getUpcomingFees($conn, $className) {

    $query = "SELECT * FROM fee_structures 

              WHERE class_name = ? AND due_date >= CURDATE() 

              ORDER BY due_date ASC LIMIT 1";

    $stmt = $conn->prepare($query);

    $stmt->bind_param("s", $className);

    $stmt->execute();

    $result = $stmt->get_result();

    $data = $result->fetch_assoc();

    $stmt->close();

    

    if ($data) {

        return [

            'fee_type' => $data['fee_type'],

            'amount' => $data['amount'],

            'due_date' => date('d M Y', strtotime($data['due_date']))

        ];

    }

    

    return null;

}



/**

 * Get student payment data

 */

function getStudentPaymentData($conn, $studentId) {

    // Get student's class first

    $classQuery = "SELECT class FROM students WHERE id = ?";

    $stmt = $conn->prepare($classQuery);

    $stmt->bind_param("i", $studentId);

    $stmt->execute();

    $classResult = $stmt->get_result();

    $studentData = $classResult->fetch_assoc();

    $stmt->close();

    

    if (!$studentData) {

        return ['total_paid' => 0, 'outstanding' => 0];

    }

    

    $className = $studentData['class'];

    

    // Get total expected fees for this class

    $expectedQuery = "SELECT SUM(amount) as total_expected FROM fee_structures WHERE class_name = ?";

    $stmt = $conn->prepare($expectedQuery);

    $stmt->bind_param("s", $className);

    $stmt->execute();

    $expectedResult = $stmt->get_result();

    $expectedData = $expectedResult->fetch_assoc();

    $stmt->close();

    

    // Get total paid by this student

    $paidQuery = "SELECT SUM(amount_paid) as total_paid FROM payments WHERE student_id = ?";

    $stmt = $conn->prepare($paidQuery);

    $stmt->bind_param("i", $studentId);

    $stmt->execute();

    $paidResult = $stmt->get_result();

    $paidData = $paidResult->fetch_assoc();

    $stmt->close();

    

    $totalExpected = $expectedData['total_expected'] ?? 0;

    $totalPaid = $paidData['total_paid'] ?? 0;

    $outstanding = max(0, $totalExpected - $totalPaid);

    

    return [

        'total_paid' => $totalPaid,

        'total_expected' => $totalExpected,

        'outstanding' => $outstanding

    ];

}



/**

 * Get current academic term

 */

function getCurrentTerm() {

    global $conn;

    $result = $conn->query(

        "SELECT setting_value FROM settings 

         WHERE setting_key = 'current_term' LIMIT 1"

    );

    if ($result && $result->num_rows > 0) {

        $row = $result->fetch_assoc();

        if (!empty($row['setting_value'])) {

            return $row['setting_value'];

        }

    }

    $month = (int) date('n');

    if ($month >= 9 && $month <= 12) return 'First Term';

    if ($month >= 1 && $month <= 4) return 'Second Term';

    return 'Third Term';

}



function getCurrentAcademicYear() {

    global $conn;

    $result = $conn->query(

        "SELECT setting_value FROM settings 

         WHERE setting_key = 'academic_year' LIMIT 1"

    );

    if ($result && $result->num_rows > 0) {

        $row = $result->fetch_assoc();

        if (!empty($row['setting_value'])) {

            return $row['setting_value'];

        }

    }

    $year = (int) date('Y');

    $month = (int) date('n');

    return $month >= 9

        ? $year . '/' . ($year + 1)

        : ($year - 1) . '/' . $year;

}





// Handle form submission for sending alerts

$message = '';

$messageType = '';



if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_alert') {

    $alert_type      = trim((string) ($_POST['alert_type']     ?? ''));

    $recipient_type  = trim((string) ($_POST['recipient_type'] ?? ''));

    $student_id      = intval($_POST['student_id'] ?? 0);

    $class_name      = trim((string) ($_POST['class_name']     ?? ''));

    $subject         = trim((string) ($_POST['subject']        ?? ''));

    $message_content = trim((string) ($_POST['message']        ?? ''));



    if (empty($alert_type) || empty($recipient_type) || empty($message_content)) {

        $message = 'Please fill all required fields';

        $messageType = 'danger';

    } else {

        // Get recipients based on type — use prepared statements

        $recipients = [];



        if ($recipient_type === 'individual' && $student_id > 0) {

            $stmt = $conn->prepare("SELECT * FROM students WHERE id = ? LIMIT 1");

            $stmt->bind_param('i', $student_id);

            $stmt->execute();

            $result = $stmt->get_result();

            if ($row = $result->fetch_assoc()) $recipients[] = $row;

            $stmt->close();

        } elseif ($recipient_type === 'class' && $class_name !== '') {

            $stmt = $conn->prepare("SELECT * FROM students WHERE class = ? AND status = 'active'");

            $stmt->bind_param('s', $class_name);

            $stmt->execute();

            $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {

                $recipients[] = $row;

            }

            $stmt->close();

        } elseif ($recipient_type === 'all') {

            $result = $conn->query("SELECT * FROM students WHERE status = 'active'");

            while ($row = $result->fetch_assoc()) {

                $recipients[] = $row;

            }

        }



        if (empty($recipients)) {

            $message = 'No recipients found';

            $messageType = 'danger';

        } else {

            $successCount = 0;

            $failCount = 0;

            

            foreach ($recipients as $recipient) {

                // Get current academic term and year

                $academicYear = getCurrentAcademicYear();

                $currentTerm = getCurrentTerm();

                

                // Get school name

                $school_name = getSetting('school_name', 'Our School');

                

                // Get fee data if needed

                $upcomingFees = getUpcomingFees($conn, $recipient['class']);

                $paymentData = getStudentPaymentData($conn, $recipient['id']);

                

                // Prepare personalizable message

                $personalized_message = $message_content;

                

                // Basic replacements

                $personalized_message = str_replace('{student_name}', trim($recipient['first_name'] . ' ' . $recipient['last_name']), $personalized_message);

                $personalized_message = str_replace('{parent_name}', $recipient['father_name'] ?: ($recipient['mother_name'] ?: 'Parent'), $personalized_message);

                $personalized_message = str_replace('{student_id}', $recipient['student_id'], $personalized_message);

                $personalized_message = str_replace('{class}', $recipient['class'], $personalized_message);

                $personalized_message = str_replace('{term}', $currentTerm, $personalized_message);

                $personalized_message = str_replace('{academic_year}', $academicYear, $personalized_message);

                $personalized_message = str_replace('{school_name}', $school_name, $personalized_message);

                

                // Fee replacements (only if we have data)

                if ($upcomingFees) {

                    $personalized_message = str_replace('{fee_type}', $upcomingFees['fee_type'], $personalized_message);

                    $personalized_message = str_replace('{amount}', formatCurrency($upcomingFees['amount']), $personalized_message);

                    $personalized_message = str_replace('{due_date}', $upcomingFees['due_date'], $personalized_message);

                } else {

                    // Remove fee placeholders if no data

                    $personalized_message = str_replace('{fee_type}', '', $personalized_message);

                    $personalized_message = str_replace('{amount}', '', $personalized_message);

                    $personalized_message = str_replace('{due_date}', '', $personalized_message);

                }

                

                // Payment data replacements

                $personalized_message = str_replace('{total_paid}', formatCurrency($paymentData['total_paid']), $personalized_message);

                $personalized_message = str_replace('{outstanding}', formatCurrency($paymentData['outstanding']), $personalized_message);

                

                // Handle exam fee block - SIMPLIFIED: only add if the template has it

                if (strpos($personalized_message, '{exam_fee_table}') !== false) {

                    // Check if there's an exam fee in fee_structures

                    $examFeeData = getClassFeeData($conn, $recipient['class']);

                    if ($examFeeData && strpos(strtolower($examFeeData['fee_type']), 'exam') !== false) {

                        $feeTable = "\n\nExam Fee: " . formatCurrency($examFeeData['amount']);

                        $personalized_message = str_replace('{exam_fee_table}', $feeTable, $personalized_message);

                    } else {

                        // Remove the placeholder completely

                        $personalized_message = str_replace('{exam_fee_table}', '', $personalized_message);

                    }

                }

                

                // Remove any remaining placeholders (that weren't replaced)

                $personalized_message = preg_replace('/\{[a-z_]+\}/', '', $personalized_message);

                

                // Clean up multiple spaces

                $personalized_message = preg_replace('/\s+/', ' ', $personalized_message);

                $personalized_message = str_replace(['\r\n', '\r', '\n'], "\n", $personalized_message);

                $personalized_message = trim($personalized_message);

                

                // Send based on alert type

                if ($alert_type === 'sms') {

                    // Clean message for SMS

                    $personalized_message = html_entity_decode($personalized_message, ENT_QUOTES, 'UTF-8');

                    $personalized_message = strip_tags($personalized_message);

                    

                    $phone = $recipient['father_phone'] ?? $recipient['mother_phone'] ?? $recipient['phone'] ?? '';

                    

                    if (!empty($phone)) {

                        $phone = formatPhoneNumber($phone);

                        $sms_sent = sendSMS($phone, $personalized_message);

                        

                        $status = $sms_sent ? 'sent' : 'failed';

                        

                        $stmt = $conn->prepare("INSERT INTO notifications (student_id, type, recipient, subject, message, status, sent_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");

                        $stmt->bind_param("isssss", $recipient['id'], $alert_type, $phone, $subject, $personalized_message, $status);

                        $stmt->execute();

                        $stmt->close();

                        

                        if ($sms_sent) $successCount++; else $failCount++;

                    } else {

                        $failCount++;

                    }

                } elseif ($alert_type === 'email') {

                    $email = $recipient['email'] ?? '';

                    if (!empty($email)) {

                        $email_sent = sendEmail($email, $subject ?: 'Notification from School', $personalized_message);

                        

                        $status = $email_sent ? 'sent' : 'failed';

                        

                        $stmt = $conn->prepare("INSERT INTO notifications (student_id, type, recipient, subject, message, status, sent_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");

                        $stmt->bind_param("isssss", $recipient['id'], $alert_type, $email, $subject, $personalized_message, $status);

                        $stmt->execute();

                        $stmt->close();

                        

                        if ($email_sent) $successCount++; else $failCount++;

                    } else {

                        $failCount++;

                    }

                } elseif ($alert_type === 'whatsapp' && function_exists('hasModule') && hasModule('whatsapp_comms')) {

                    require_once __DIR__ . '/includes/whatsapp_lib.php';

                    $personalized_message = html_entity_decode($personalized_message, ENT_QUOTES, 'UTF-8');

                    $personalized_message = strip_tags($personalized_message);

                    $phone = $recipient['father_phone'] ?? $recipient['mother_phone'] ?? $recipient['phone'] ?? '';

                    if (!empty($phone)) {

                        $wa      = sendWhatsApp($phone, $personalized_message);

                        $wa_sent = !empty($wa['success']);

                        $status  = $wa_sent ? 'sent' : 'failed';

                        $waPhone = wa_format_phone($phone);

                        $stmt = $conn->prepare("INSERT INTO notifications (student_id, type, recipient, subject, message, status, sent_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");

                        $stmt->bind_param("isssss", $recipient['id'], $alert_type, $waPhone, $subject, $personalized_message, $status);

                        $stmt->execute();

                        $stmt->close();

                        if ($wa_sent) $successCount++; else $failCount++;

                    } else {

                        $failCount++;

                    }

                }

            }

            

            if ($successCount > 0) {

                $message = "Alert sent to $successCount recipient(s) successfully";

                if ($failCount > 0) $message .= ". Failed for $failCount recipient(s).";

                $messageType = 'success';

            } else {

                $message = 'Failed to send alerts to any recipient';

                $messageType = 'danger';

            }

        }

    }

}



// Get data for display

$sms_logs = [];

$result = $conn->query("SELECT * FROM sms_logs ORDER BY created_at DESC");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $sms_logs[] = $row;

    }

}



$notifications = [];

$result = $conn->query("SELECT n.*, s.first_name, s.last_name 

                        FROM notifications n 

                        LEFT JOIN students s ON n.student_id = s.id 

                        ORDER BY n.sent_at DESC");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $notifications[] = $row;

    }

}



$students = [];

$result = $conn->query("SELECT id, student_id, first_name, last_name, class, father_name, mother_name, father_phone, mother_phone, phone, email FROM students WHERE status = 'active' ORDER BY first_name, last_name");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        // Create a parent_name field for display

        $row['parent_name'] = $row['father_name'] ?: $row['mother_name'] ?: 'N/A';

        $students[] = $row;

    }

}



// Classes — primary: Class Management; fallback: students

$classes = [];

$result = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");

if ($result) { while ($row = $result->fetch_assoc()) $classes[] = $row['class_name']; }

$result2 = $conn->query("SELECT DISTINCT class FROM students WHERE status = 'active' AND class IS NOT NULL ORDER BY class");

if ($result2) { while ($row = $result2->fetch_assoc()) { if (!in_array($row['class'], $classes)) $classes[] = $row['class']; } }

sort($classes);



$conn->close();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>SMS & Email Alerts - SchoolFinance Pro</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">

    <link rel="stylesheet" href="css/style.css">

    <style>

        .placeholder-badge {

            background: #e8f4fd;

            color: #3498db;

            padding: 3px 8px;

            border-radius: 4px;

            font-size: 12px;

            cursor: pointer;

            margin: 2px;

            display: inline-block;

        }

        .placeholder-badge:hover {

            background: #3498db;

            color: white;

        }

        .placeholders-container {

            margin-top: 10px;

            padding: 10px;

            background: #f8f9fa;

            border-radius: 8px;

        }

        .dt-buttons {

            margin-bottom: 15px;

        }

        .status-badge {

            padding: 5px 10px;

            border-radius: 20px;

            font-size: 12px;

            font-weight: 500;

        }

        .status-badge.success {

            background: #d4edda;

            color: #155724;

        }

        .status-badge.failed {

            background: #f8d7da;

            color: #721c24;

        }

        .status-badge.pending {

            background: #fff3cd;

            color: #856404;

        }

    </style>

</head>

<body>

    <div class="wrapper">

        <!-- Sidebar -->

        <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>

        </nav>



        <!-- Main Content -->

        <div class="main-content">

            <!-- Header -->

            <header class="header">

                <button class="btn-toggle" id="sidebarToggle">

                    <i class="fas fa-bars"></i>

                </button>

                <div class="header-right">

                    <div class="dropdown">

                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>

                        </button>

                        <ul class="dropdown-menu dropdown-menu-end">

                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>

                            <li><hr class="dropdown-divider"></li>

                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>

                        </ul>

                    </div>

                </div>

            </header>



            <!-- Page Content -->

            <main class="content">

                <div class="content-header">

                    <h2><i class="fas fa-bell me-2"></i>SMS & Email Alerts</h2>

                    <p>Send notifications to students and parents</p>

                </div>



                <!-- Alert Message -->

                <?php if ($message): ?>

                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">

                    <?php echo $message; ?>

                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

                </div>

                <?php endif; ?>



                <!-- Tabs -->

                <ul class="nav nav-tabs" id="alertTabs" role="tablist">

                    <li class="nav-item">

                        <button class="nav-link active" id="send-tab" data-bs-toggle="tab" data-bs-target="#send" type="button">

                            <i class="fas fa-paper-plane me-2"></i>Send Alert

                        </button>

                    </li>

                    <li class="nav-item">

                        <button class="nav-link" id="templates-tab" data-bs-toggle="tab" data-bs-target="#templates" type="button">

                            <i class="fas fa-file-alt me-2"></i>Templates

                        </button>

                    </li>

                    <li class="nav-item">

                        <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button">

                            <i class="fas fa-history me-2"></i>Notification Logs

                        </button>

                    </li>

                    

                     <li class="nav-item">

                        <button class="nav-link" id="sms-tab" data-bs-toggle="tab" data-bs-target="#sms" type="button">

                            <i class="fas fa-history me-2"></i>SMS Logs

                        </button>

                    </li>

                </ul>



                <div class="tab-content" id="alertTabsContent">

                    <!-- Send Alert Tab -->

                    <div class="tab-pane fade show active" id="send" role="tabpanel">

                        <div class="row">

                            <div class="col-lg-8">

                                <div class="card">

                                    <div class="card-header">

                                        <h5><i class="fas fa-envelope me-2"></i>Send New Alert</h5>

                                    </div>

                                    <div class="card-body">

                                        <form method="POST" action="alerts.php" id="sendAlertForm">

                                            <input type="hidden" name="action" value="send_alert">

                                            

                                            <div class="row">

                                                <div class="col-md-6 mb-3">

                                                    <label class="form-label">Alert Type *</label>

                                                    <select class="form-select" name="alert_type" id="alertType" required>

                                                        <option value="">Select Type</option>

                                                        <option value="sms">SMS</option>

                                                        <option value="email">Email</option>

                                                        <?php if (function_exists('hasModule') && hasModule('whatsapp_comms')): ?>

                                                        <option value="whatsapp">WhatsApp</option>

                                                        <?php endif; ?>

                                                    </select>

                                                </div>

                                                <div class="col-md-6 mb-3">

                                                    <label class="form-label">Recipients *</label>

                                                    <select class="form-select" name="recipient_type" id="recipientType" required>

                                                        <option value="">Select Recipients</option>

                                                        <option value="individual">Individual Student</option>

                                                        <option value="class">Whole Class</option>

                                                        <option value="all">All Students</option>

                                                    </select>

                                                </div>

                                            </div>

                                            

                                            <div class="mb-3" id="individualRecipients" style="display:none;">

                                                <label class="form-label">Select Student *</label>

                                                <select class="form-select" name="student_id">

                                                    <option value="">Select Student</option>

                                                    <?php foreach ($students as $student): ?>

                                                        <option value="<?php echo $student['id']; ?>">

                                                            <?php echo $student['first_name'] . ' ' . $student['last_name'] . ' (' . $student['student_id'] . ') - Parent: ' . ($student['parent_name'] ?: 'N/A'); ?>

                                                        </option>

                                                    <?php endforeach; ?>

                                                </select>

                                            </div>

                                            

                                            <div class="mb-3" id="classRecipients" style="display:none;">

                                                <label class="form-label">Select Class *</label>

                                                <select class="form-select" name="class_name">

                                                    <option value="">Select Class</option>

                                                    <?php foreach ($classes as $class): ?>

                                                        <option value="<?php echo $class; ?>"><?php echo $class; ?></option>

                                                    <?php endforeach; ?>

                                                </select>

                                            </div>



                                            <div class="mb-3">

                                                <label class="form-label">Subject (For Email)</label>

                                                <input type="text" class="form-control" name="subject" placeholder="Enter subject">

                                            </div>



                                            <div class="mb-3">

                                                <label class="form-label">Message *</label>

                                                <textarea class="form-control" name="message" id="messageText" rows="5" placeholder="Enter your message" required></textarea>

                                            </div>



                                            <div class="mb-3">

                                                <label class="form-label">Use Template (Optional)</label>

                                                <select class="form-select" id="templateSelect">

                                                    <option value="">Select Template</option>

                                                    <option value="fee_due">Fee Due Reminder</option>

                                                    <option value="payment_received">Payment Received</option>

                                                    <option value="welcome">Welcome Message</option>

                                                    <option value="fee_overdue">Fee Overdue Notice</option>

                                                    <option value="event">Event/Meeting Notice</option>

                                                    <option value="exam">Examination Notice</option>

                                                </select>

                                            </div>



                                            <div class="placeholders-container">

                                                <small class="text-muted">Click to insert placeholders:</small>

                                                <div>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{student_name}')">{student_name}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{parent_name}')">{parent_name}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{student_id}')">{student_id}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{school_name}')">{school_name}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{amount}')">{amount}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{fee_type}')">{fee_type}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{due_date}')">{due_date}</span>

                                                    <span class="placeholder-badge" onclick="insertPlaceholder('{class}')">{class}</span>

                                                </div>

                                                <small class="text-muted">Placeholders will be replaced with actual values when sending</small>

                                            </div>



                                            <button type="submit" class="btn btn-primary mt-3">

                                                <i class="fas fa-paper-plane me-2"></i>Send Alert

                                            </button>

                                        </form>

                                    </div>

                                </div>

                            </div>

                            

                            <div class="col-lg-4">

                                <div class="card">

                                    <div class="card-header">

                                        <h5><i class="fas fa-info-circle me-2"></i>Quick Info</h5>

                                    </div>

                                    <div class="card-body">

                                        <div class="alert alert-info">

                                            <i class="fas fa-sms me-2"></i> SMS will be sent using Arkesel API

                                        </div>

                                        <div class="alert alert-info">

                                            <i class="fas fa-envelope me-2"></i> Email will be sent using SMTP

                                        </div>

                                        <hr>

                                        <h6>Available Recipients</h6>

                                        <p class="text-muted mb-1">Total Students: <?php echo count($students); ?></p>

                                        <p class="text-muted mb-1">With Phone: <?php echo count(array_filter($students, function($s) { return !empty($s['father_phone']); })); ?></p>

                                        <p class="text-muted">With Email: <?php echo count(array_filter($students, function($s) { return !empty($s['father_email']); })); ?></p>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>



                    <!-- Templates Tab -->

                    <div class="tab-pane fade" id="templates" role="tabpanel">

                        <div class="row">

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-bell me-2"></i>Fee Due Reminder</h6>

                                    <p class="text-muted mb-2">Remind parents about upcoming fee due date</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('fee_due')">Use Template</button>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-check-circle me-2"></i>Payment Received</h6>

                                    <p class="text-muted mb-2">Confirm payment receipt</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('payment_received')">Use Template</button>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-user-plus me-2"></i>Welcome Message</h6>

                                    <p class="text-muted mb-2">Welcome new students</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('welcome')">Use Template</button>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Fee Overdue</h6>

                                    <p class="text-muted mb-2">Notice for overdue fees</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('fee_overdue')">Use Template</button>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-calendar-alt me-2"></i>Event Notice</h6>

                                    <p class="text-muted mb-2">School events and meetings</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('event')">Use Template</button>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <div class="alert-card">

                                    <h6><i class="fas fa-pencil-alt me-2"></i>Exam Notice</h6>

                                    <p class="text-muted mb-2">Examination schedules</p>

                                    <button class="btn btn-sm btn-primary" onclick="useTemplate('exam')">Use Template</button>

                                </div>

                            </div>

                        </div>

                    </div>



                    <!-- Notification Logs Tab -->

                    <div class="tab-pane fade" id="history" role="tabpanel">

                        <div class="card">

                            <div class="card-header">

                                <h5><i class="fas fa-history me-2"></i>Notification Logs</h5>

                            </div>

                            <div class="card-body">

                                <div class="table-responsive">

                                    <table class="table table-hover" id="notificationsTable">

                                        <thead>

                                            <tr>

                                                <th>Date/Time</th>

                                                <th>Type</th>

                                                <th>Recipient</th>

                                                <th>Student</th>

                                                <th>Message</th>

                                                <th>Status</th>

                                                <th>Actions</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php if (empty($notifications)): ?>

                                                <tr>

                                                    <td colspan="7" class="text-center py-4">

                                                        <div class="empty-state">

                                                            <i class="fas fa-bell"></i>

                                                            <h4>No Notifications</h4>

                                                            <p>Sent notifications will appear here</p>

                                                        </div>

                                                    </td>

                                                </tr>

                                            <?php else: ?>

                                                <?php foreach ($notifications as $log): ?>

                                                <tr>

                                                    <td><?php echo date('d M Y H:i', strtotime($log['sent_at'])); ?></td>

                                                    <td>

                                                        <span class="badge bg-<?php echo $log['type'] === 'sms' ? 'info' : 'warning'; ?>">

                                                            <?php echo strtoupper($log['type']); ?>

                                                        </span>

                                                    </td>

                                                    <td><?php echo htmlspecialchars($log['recipient']); ?></td>

                                                    <td>

                                                        <?php 

                                                        if ($log['student_id']) {

                                                            echo htmlspecialchars($log['first_name'] . ' ' . $log['last_name']);

                                                        } else {

                                                            echo '-';

                                                        }

                                                        ?>

                                                    </td>

                                                    <td>

                                                        <span title="<?php echo htmlspecialchars($log['message']); ?>">

                                                            <?php echo htmlspecialchars(substr($log['message'], 0, 50)) . '...'; ?>

                                                        </span>

                                                    </td>

                                                    <td>

                                                        <span class="status-badge <?php echo $log['status']; ?>">

                                                            <?php echo ucfirst($log['status']); ?>

                                                        </span>

                                                    </td>

                                                    <td>

                                                        <button class="action-btn view" onclick="viewNotification(<?php echo $log['id']; ?>)" title="View Details">

                                                            <i class="fas fa-eye"></i>

                                                        </button>

                                                    </td>

                                                </tr>

                                                <?php endforeach; ?>

                                            <?php endif; ?>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                        </div>

                    </div>

                    

                    <!-- SMS Logs Tab -->

                    <div class="tab-pane fade" id="sms" role="tabpanel">

    <div class="card">

        <div class="card-header">

            <h5><i class="fas fa-history me-2"></i>SMS History</h5>

        </div>

        <div class="card-body">

            <div class="table-responsive">

                <table class="table table-hover" id="smsTable">

                    <thead>

                        <tr>

                            <th>Date</th>

                            <th>Phone Number</th>

                            <th>Message</th>

                            <th>Status</th>

                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php if (empty($sms_logs)): ?>

                            <tr>

                                <td colspan="5" class="text-center py-4">

                                    <div class="empty-state">

                                        <i class="fas fa-sms"></i>

                                        <h4>No SMS History</h4>

                                        <p>Sent SMS messages will appear here</p>

                                    </div>

                                </td>

                            </tr>

                        <?php else: ?>

                            <?php foreach ($sms_logs as $log): ?>

                            <tr>

                                <td><?php echo date('d M Y H:i', strtotime($log['created_at'])); ?></td>

                                <td><?php echo htmlspecialchars($log['phone']); ?></td>

                                <td><?php echo htmlspecialchars(substr($log['message'], 0, 50)) . '...'; ?></td>

                                <td>

                                    <span class="badge bg-<?php echo $log['status'] === 'Success' ? 'success' : 'danger'; ?>">

                                        <?php echo htmlspecialchars($log['status']); ?>

                                    </span>

                                </td>

                                <td>

                                    <button class="action-btn view" onclick="viewSMS(<?php echo $log['id']; ?>)" title="View Full Message">

                                        <i class="fas fa-eye"></i>

                                    </button>

                                </td>

                            </tr>

                            <?php endforeach; ?>

                        <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

                </div>

            </main>



            <!-- Footer -->

            <footer class="footer">

                <p>&copy; 2024 SchoolFinance Pro. All rights reserved.</p>

            </footer>

        </div>

    </div>



    <!-- View Notification Modal -->

    <div class="modal fade" id="viewNotificationModal" tabindex="-1">

        <div class="modal-dialog modal-lg">

            <div class="modal-content">

                <div class="modal-header">

                    <h5 class="modal-title"><i class="fas fa-envelope me-2"></i>Notification Details</h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                </div>

                <div class="modal-body" id="viewNotificationContent">

                    <p class="text-center">Loading...</p>

                </div>

                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

                </div>

            </div>

        </div>

    </div>

    

    <!-- View SMS Modal -->

<div class="modal fade" id="viewSMSModal" tabindex="-1">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">

                <h5 class="modal-title"><i class="fas fa-sms me-2"></i>SMS Message Details</h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>

            <div class="modal-body" id="viewSMSContent">

                <!-- Content loaded via AJAX -->

                <p class="text-center">Loading...</p>

            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

            </div>

        </div>

    </div>

</div>



    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>

    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>

    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>

    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

    <script src="js/main.js"></script>

    <script>

        $(document).ready(function() {

            // Initialize DataTable for notifications

            $('#notificationsTable').DataTable({

                pageLength: 25,

                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],

                order: [[0, 'desc']],

                dom: 'Bfrtip',

                buttons: [

                    {

                        extend: 'excel',

                        text: '<i class="fas fa-file-excel me-2"></i>Export to Excel',

                        className: 'btn btn-success btn-sm',

                        exportOptions: {

                            columns: [0, 1, 2, 3, 4, 5]

                        }

                    },

                    {

                        extend: 'pdf',

                        text: '<i class="fas fa-file-pdf me-2"></i>Export to PDF',

                        className: 'btn btn-danger btn-sm',

                        exportOptions: {

                            columns: [0, 1, 2, 3, 4, 5]

                        }

                    },

                    {

                        extend: 'print',

                        text: '<i class="fas fa-print me-2"></i>Print',

                        className: 'btn btn-info btn-sm'

                    }

                ],

                language: {

                    emptyTable: "No notification records found"

                }

            });

            

             $('#smsTable').DataTable({

                pageLength: 10,

                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],

                order: [[0, 'desc']],

                dom: 'Bfrtip',

                buttons: [

                    {

                        extend: 'excel',

                        text: '<i class="fas fa-file-excel me-2"></i>Export to Excel',

                        className: 'btn btn-success btn-sm',

                        exportOptions: {

                            columns: [0, 1, 2, 3, 4, 5]

                        }

                    },

                    {

                        extend: 'pdf',

                        text: '<i class="fas fa-file-pdf me-2"></i>Export to PDF',

                        className: 'btn btn-danger btn-sm',

                        exportOptions: {

                            columns: [0, 1, 2, 3, 4, 5]

                        }

                    },

                    {

                        extend: 'print',

                        text: '<i class="fas fa-print me-2"></i>Print',

                        className: 'btn btn-info btn-sm'

                    }

                ],

                language: {

                    emptyTable: "No sms records found"

                }

            });



            // NOTE: Recipient-type toggle is handled by a standalone vanilla-JS
            // block below (independent of jQuery/DataTables), so it keeps
            // working even if a CDN script fails to load. Do not re-bind here.

            // Template selection

            $('#templateSelect').on('change', function() {

                const template = $(this).val();

                if (template) {

                    useTemplate(template);

                }

            });

        });



        // Template content with placeholders

       // Template content with placeholders - OPTIMIZED FOR SMS (no HTML)

// Template content with ALL placeholders

const templates = {

    fee_due: 'Dear {parent_name},\n\nThis is a reminder that the {fee_type} of {amount} for {student_name} ({class}) is due on {due_date}.\n\nCurrent outstanding balance: {outstanding}\n\nPlease make payment promptly to avoid any inconvenience.\n\nThank you.\n- {school_name}',

    

    payment_received: 'Dear {parent_name},\n\nWe have received your payment of {amount} for {student_name} ({fee_type}).\n\nTotal paid so far: {total_paid}\nOutstanding balance: {outstanding}\n\nThank you for your prompt payment.\n\n- {school_name}',

    

    welcome: 'Dear {parent_name},\n\nWelcome to {school_name}! We are delighted to have {student_name} as part of our school family in {class}.\n\nAcademic Year: {academic_year}\nCurrent Term: {term}\n\nWe look forward to a wonderful academic journey together.\n\n- School Administration',

    

    fee_overdue: 'Dear {parent_name},\n\nURGENT: This is to inform you that the {fee_type} of {amount} for {student_name} ({class}) is now overdue.\n\nOutstanding balance: {outstanding}\n\nKindly clear the pending amount immediately to avoid any disruption.\n\n- {school_name}',

    

    event: 'Dear {parent_name},\n\nThis is to inform you about an upcoming event at {school_name} for {student_name}\'s class ({class}).\n\nPlease check the school notice board for details.\n\nThank you.\n- School Administration',

    

    exam: 'Dear {parent_name},\n\nThis is to inform you that examinations ({term}) will commence from next week for {student_name}\'s class ({class}).\n\n{exam_fee_table}\nKindly ensure regular attendance and preparation.\n\n- School Administration'

};



        function useTemplate(templateKey) {

            const template = templates[templateKey];

            if (template) {

                $('#messageText').val(template);

                showToast('Template applied', 'success');

            }

        }



        // Insert placeholder at cursor position

        function insertPlaceholder(placeholder) {

            const textarea = document.getElementById('messageText');

            const start = textarea.selectionStart;

            const end = textarea.selectionEnd;

            const text = textarea.value;

            const before = text.substring(0, start);

            const after = text.substring(end, text.length);

            textarea.value = before + placeholder + after;

            textarea.selectionStart = textarea.selectionEnd = start + placeholder.length;

            textarea.focus();

        }



        // Form submission with loader

        $('#sendAlertForm').on('submit', function() {

            showLoader();

            return true;

        });



        // View notification function

        function viewNotification(id) {

            $('#viewNotificationModal').modal('show');

            $('#viewNotificationContent').html('<p class="text-center"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</p>');

            

            $.ajax({

                url: 'ajax/notifications.php?action=view&id=' + id,

                type: 'GET',

                success: function(response) {

                    $('#viewNotificationContent').html(response);

                },

                error: function() {

                    $('#viewNotificationContent').html('<p class="text-danger">Failed to load notification details</p>');

                }

            });

        }

        

         // View SMS function

function viewSMS(id) {

    $('#viewSMSModal').modal('show');

    $('#viewSMSContent').html('<p class="text-center">Loading...</p>');

    

    $.ajax({

        url: 'ajax/sms.php?action=view&id=' + id,

        type: 'GET',

        success: function(response) {

            $('#viewSMSContent').html(response);

        },

        error: function() {

            $('#viewSMSContent').html('<p class="text-danger">Failed to load SMS details</p>');

        }

    });

}

    </script>

    <!-- Standalone recipient-type toggle: no jQuery/DataTables dependency, so
         the Individual/Class sub-dropdowns always appear even if a CDN fails -->
    <script>
    (function () {
        function toggleRecipientFields(value) {
            var ind = document.getElementById('individualRecipients');
            var cls = document.getElementById('classRecipients');
            if (ind) ind.style.display = (value === 'individual') ? 'block' : 'none';
            if (cls) cls.style.display = (value === 'class') ? 'block' : 'none';
        }
        function init() {
            var sel = document.getElementById('recipientType');
            if (!sel) return;
            sel.addEventListener('change', function () { toggleRecipientFields(this.value); });
            // Restore state on load (e.g. after a failed POST re-render)
            toggleRecipientFields(sel.value);
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', init);
        } else {
            init();
        }
    })();
    </script>
</body>

</html>

