<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch patients for selection
$p_res = $conn->query("SELECT p.patient_id, u.full_name, p.phone_number FROM patients p JOIN users u ON p.user_id = u.user_id WHERE p.phone_number IS NOT NULL AND p.phone_number != '' LIMIT 100");

// Fetch Templates
$t_res = $conn->query("SELECT * FROM communication_templates WHERE type='SMS'");

if (isset($_POST['send_sms'])) {
    $patient_id = $_POST['patient_id'];
    $message = htmlspecialchars($_POST['message']);

    // Simulate Sending SMS (In production, use API like Twilio/Africa's Talking)
    // Log the communication
    $conn->begin_transaction();
    try {
        // Get patient phone
        $pat = $conn->query("SELECT phone_number FROM patients WHERE patient_id=$patient_id")->fetch_assoc();

        // Log to existing audit log or communication_log if it exists. 
        // Based on menu_config, 'communication_log.php' exists, so likely a table 'communication_logs' or similar.
        // I'll assume 'communication_logs' or just use 'activity_log' for now if specific table unknown.
        // Actually, generic activity log:
        $stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, module, description, record_id) VALUES (?, 'SEND_SMS', 'COMMUNICATION', ?, ?)");
        $desc = "Sent SMS to " . $pat['phone_number'];
        $stmt->bind_param("isi", $_SESSION['user_id'], $desc, $patient_id);
        $stmt->execute();

        $conn->commit();
        $_SESSION['success'] = "SMS Sent successfully (Simulated)";
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = "Error sending SMS";
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Send SMS')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Send SMS Notification</h4>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success"><?php echo $_SESSION['success'];
                        unset($_SESSION['success']); ?>
                        </div>
                    <?php endif; ?>

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card">
                                <div class="card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Recipient (Patient)</label>
                                            <select class="form-select select2" name="patient_id" required>
                                                <option value="">Select Patient...</option>
                                                <?php while ($p = $p_res->fetch_assoc()): ?>
                                                    <option value="<?php echo $p['patient_id']; ?>">
                                                        <?php echo htmlspecialchars($p['full_name'] . ' (' . $p['phone_number'] . ')'); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Template (Optional)</label>
                                            <select class="form-select" id="templateSelect">
                                                <option value="">Select Template...</option>
                                                <?php while ($t = $t_res->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($t['content']); ?>">
                                                        <?php echo htmlspecialchars($t['template_name']); ?></option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Message</label>
                                            <textarea class="form-control" name="message" id="messageBox" rows="4"
                                                required maxlength="160"></textarea>
                                            <div class="form-text">Max 160 characters.</div>
                                        </div>
                                        <button type="submit" name="send_sms" class="btn btn-primary w-100">Send
                                            Message</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.select2').select2();
            $('#templateSelect').change(function () {
                var content = $(this).val();
                if (content) $('#messageBox').val(content);
            });
        });
    </script>
</body>

</html>