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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions. Not Authorized.']);
    exit;
}

try {
    $template_id = $_POST['template_id'] ?? null;
    $is_update = !empty($template_id);
    
    if ($is_update) {
        $sql = "UPDATE notification_templates SET 
                template_name = ?,
                template_code = ?,
                subject_template = ?,
                body_template = ?,
                sms_template = ?,
                days_before = ?
                WHERE template_id = ?";
                
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssssis',
            $_POST['template_name'],
            $_POST['template_code'],
            $_POST['subject_template'],
            $_POST['body_template'],
            $_POST['sms_template'],
            $_POST['days_before'],
            $template_id
        );
    } else {
        $sql = "INSERT INTO notification_templates (
                template_name, template_code, subject_template, 
                body_template, sms_template, days_before
                ) VALUES (?, ?, ?, ?, ?, ?)";
                
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssssi',
            $_POST['template_name'],
            $_POST['template_code'],
            $_POST['subject_template'],
            $_POST['body_template'],
            $_POST['sms_template'],
            $_POST['days_before']
        );
    }
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to save template: " . $stmt->error);
    }
    
    echo json_encode([
        'success' => true,
        'message' => $is_update ? 'Template updated successfully' : 'Template created successfully'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>

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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $setting_id = $_POST['setting_id'] ?? null;
    $is_update = !empty($setting_id);
    
    // Validate recipient type and value
    $recipient_type = $_POST['recipient_type'];
    $recipient_value = $_POST['recipient_value'];
    
    switch ($recipient_type) {
        case 'EMAIL':
            if (!filter_var($recipient_value, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Invalid email address');
            }
            break;
        case 'PHONE':
            // Basic phone validation - modify as needed
            if (!preg_match('/^\+?[\d\s-]{10,}$/', $recipient_value)) {
                throw new Exception('Invalid phone number');
            }
            break;
    }
    
    if ($is_update) {
        $sql = "UPDATE notification_settings SET 
                template_id = ?,
                recipient_type = ?,
                recipient_value = ?,
                notify_via_email = ?,
                notify_via_sms = ?
                WHERE setting_id = ?";
                
        $stmt = $conn->prepare($sql);
        $email = isset($_POST['notify_via_email']) ? 1 : 0;
        $sms = isset($_POST['notify_via_sms']) ? 1 : 0;
        
        $stmt->bind_param('isssii',
            $_POST['template_id'],
            $recipient_type,
            $recipient_value,
            $email,
            $sms,
            $setting_id
        );
    } else {
        $sql = "INSERT INTO notification_settings (
                template_id, recipient_type, recipient_value,
                notify_via_email, notify_via_sms, created_by
                ) VALUES (?, ?, ?, ?, ?, ?)";
                
        $stmt = $conn->prepare($sql);
        $email = isset($_POST['notify_via_email']) ? 1 : 0;
        $sms = isset($_POST['notify_via_sms']) ? 1 : 0;
        
        $stmt->bind_param('isssii',
            $_POST['template_id'],
            $recipient_type,
            $recipient_value,
            $email,
            $sms,
            $_SESSION['user_id']
        );
    }
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to save recipient: " . $stmt->error);
    }
    
    echo json_encode([
        'success' => true,
        'message' => $is_update ? 'Recipient updated successfully' : 'Recipient added successfully'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>

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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $template_id = $_GET['id'] ?? null;
    if (!$template_id) {
        throw new Exception('Template ID is required');
    }

    $sql = "SELECT * FROM notification_templates WHERE template_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $template_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $template = $result->fetch_assoc();

    if (!$template) {
        throw new Exception('Template not found');
    }

    echo json_encode([
        'success' => true,
        'template' => $template
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>

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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $setting_id = $_GET['id'] ?? null;
    if (!$setting_id) {
        throw new Exception('Setting ID is required');
    }

    $sql = "SELECT * FROM notification_settings WHERE setting_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $setting_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $recipient = $result->fetch_assoc();

    if (!$recipient) {
        throw new Exception('Recipient not found');
    }

    echo json_encode([
        'success' => true,
        'recipient' => $recipient
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>

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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $template_id = $_POST['template_id'] ?? null;
    if (!$template_id) {
        throw new Exception('Template ID is required');
    }

    // Start transaction
    $conn->begin_transaction();

    // Delete associated settings first
    $sql = "DELETE FROM notification_settings WHERE template_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $template_id);
    $stmt->execute();

    // Delete template
    $sql = "DELETE FROM notification_templates WHERE template_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $template_id);
    $stmt->execute();

    // Commit transaction
    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Template deleted successfully'
    ]);

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>

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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    $setting_id = $_POST['setting_id'] ?? null;
    if (!$setting_id) {
        throw new Exception('Setting ID is required');
    }

    $sql = "DELETE FROM notification_settings WHERE setting_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $setting_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to delete recipient: " . $stmt->error);
    }

    echo json_encode([
        'success' => true,
        'message' => 'Recipient deleted successfully'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>