<?php
session_start();

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

$title = 'Announcements';

require_once '../config/database.php';
require_once '../includes/app_helpers.php';

$database = new Database();
$db = $database->getConnection();

ensureCsrTeamTables($db);
ensureAnnouncementTables($db);

$managerId = (int)$_SESSION['csr_id'];

if (!isCsrManager($db, $managerId)) {
    http_response_code(403);
    echo 'Only CSR Managers can access this page.';
    exit;
}

$message = '';
$error = '';

if (!empty($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

if (!empty($_SESSION['flash_error'])) {
    $error = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

$teamStmt = $db->prepare("
    SELECT 
        id, 
        team_name 
    FROM csr_teams 
    WHERE manager_id = :manager_id 
      AND is_active = 1 
    ORDER BY team_name
");

$teamStmt->execute([
    ':manager_id' => $managerId
]);

$managerTeams = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
$singleTeam = count($managerTeams) === 1 ? $managerTeams[0] : null;

function shortAnnouncementText($text, $limit = 90) {
    $text = trim((string)$text);

    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($text, 0, $limit, '...');
    }

    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
}

function managerOwnsAnnouncement(PDO $db, int $announcementId, int $managerId): bool {
    $stmt = $db->prepare("
        SELECT ca.id
        FROM csr_announcements ca
        LEFT JOIN csr_teams ct ON ct.id = ca.team_id
        WHERE ca.id = :id
          AND (
                ca.created_by = :manager_id
                OR ct.manager_id = :manager_id_team
          )
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $announcementId,
        ':manager_id' => $managerId,
        ':manager_id_team' => $managerId
    ]);

    return (bool)$stmt->fetch(PDO::FETCH_ASSOC);
}

function redirectWithMessage(string $message): void {
    $_SESSION['flash_message'] = $message;
    header('Location: manager_announcements.php');
    exit;
}

function redirectWithError(string $error): void {
    $_SESSION['flash_error'] = $error;
    header('Location: manager_announcements.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['create_announcement'])) {
            $titleText = trim($_POST['title'] ?? '');
            $body = trim($_POST['message'] ?? '');
            $priority = $_POST['priority'] ?? 'info';
            $expires = trim($_POST['expires_at'] ?? '');
            $teamId = (int)($_POST['team_id'] ?? 0);

            if ($titleText === '' || $body === '') {
                throw new Exception('Title and message are required.');
            }

            if (!in_array($priority, ['info', 'success', 'warning', 'danger'], true)) {
                $priority = 'info';
            }

            if (!$managerTeams) {
                throw new Exception('You do not have an active team yet. Ask the admin to create a team and assign regular CSRs under you.');
            }

            if ($singleTeam) {
                $teamId = (int)$singleTeam['id'];
            }

            $allowedTeamIds = array_map('intval', array_column($managerTeams, 'id'));

            if (!in_array($teamId, $allowedTeamIds, true)) {
                throw new Exception('Please select one of your assigned teams.');
            }

            $stmt = $db->prepare("
                INSERT INTO csr_announcements 
                    (team_id, title, message, priority, created_by, expires_at, is_active) 
                VALUES 
                    (:team_id, :title, :message, :priority, :created_by, :expires_at, 1)
            ");

            $stmt->execute([
                ':team_id' => $teamId,
                ':title' => $titleText,
                ':message' => $body,
                ':priority' => $priority,
                ':created_by' => $managerId,
                ':expires_at' => $expires ?: null
            ]);

            redirectWithMessage('Announcement posted. It will pop up for unread regular CSRs in your team.');
        }

        if (isset($_POST['toggle_announcement'])) {
            $id = (int)($_POST['announcement_id'] ?? 0);

            if ($id <= 0 || !managerOwnsAnnouncement($db, $id, $managerId)) {
                throw new Exception('Announcement not found or you do not have permission to update it.');
            }

            $stmt = $db->prepare("
                UPDATE csr_announcements
                SET is_active = IF(is_active = 1, 0, 1)
                WHERE id = :id
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            redirectWithMessage('Announcement status updated.');
        }

        if (isset($_POST['delete_announcement'])) {
            $id = (int)($_POST['announcement_id'] ?? 0);

            if ($id <= 0 || !managerOwnsAnnouncement($db, $id, $managerId)) {
                throw new Exception('Announcement not found or you do not have permission to delete it.');
            }

            $db->beginTransaction();

            $deleteReads = $db->prepare("
                DELETE FROM csr_announcement_reads
                WHERE announcement_id = :id
            ");

            $deleteReads->execute([
                ':id' => $id
            ]);

            $deleteAnnouncement = $db->prepare("
                DELETE FROM csr_announcements
                WHERE id = :id
            ");

            $deleteAnnouncement->execute([
                ':id' => $id
            ]);

            $db->commit();

            redirectWithMessage('Announcement deleted successfully.');
        }

        redirectWithError('Invalid announcement action.');
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }

        redirectWithError($e->getMessage());
    }
}

$annStmt = $db->prepare("
    SELECT 
        ca.*, 
        CONCAT(cu.first_name, ' ', cu.last_name) AS created_by_name,
        ct.team_name
    FROM csr_announcements ca
    LEFT JOIN csr_users cu ON cu.id = ca.created_by
    LEFT JOIN csr_teams ct ON ct.id = ca.team_id
    WHERE ca.created_by = :manager_id 
       OR ct.manager_id = :manager_id_team
    ORDER BY ca.created_at DESC
    LIMIT 100
");

$annStmt->execute([
    ':manager_id' => $managerId,
    ':manager_id_team' => $managerId
]);

$ann = $annStmt->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>

<style>
    .announcement-shell {
        display: grid;
        gap: 16px;
    }

    .ann-card {
        background: linear-gradient(135deg, #17295e, #102448);
        border: 1px solid rgba(56, 189, 248, .24);
        border-radius: 16px;
        padding: 16px;
        color: #fff;
        box-shadow:
            0 10px 24px rgba(0, 0, 0, 0.22),
            inset 0 0 0 1px rgba(255, 255, 255, 0.025);
    }

    .ann-card h2,
    .ann-card h4 {
        font-weight: 900;
        color: #ffffff !important;
    }

    .text-muted {
        color: #aebbd4 !important;
    }

    .form-label {
        color: #ffffff !important;
        font-weight: 800 !important;
    }

    .form-control,
    .form-select {
        background: rgba(8, 20, 48, .72) !important;
        border: 1px solid rgba(96, 165, 250, .34) !important;
        color: #fff !important;
        border-radius: 10px !important;
        min-height: 42px;
    }

    .form-control::placeholder {
        color: #aebbd4 !important;
    }

    .form-select option {
        background: #102448;
        color: #fff;
    }

    .team-target-box {
        background: rgba(8, 20, 48, 0.45);
        border: 1px solid rgba(96, 165, 250, .26);
        border-radius: 12px;
        padding: 10px 12px;
        color: #d7e7ff;
        font-weight: 800;
        min-height: 42px;
        display: flex;
        align-items: center;
    }

    .team-target-box i {
        color: #17bdd4;
    }

    .btn-main {
        background: linear-gradient(135deg, #1d9bf0, #17bdd4);
        border: none;
        border-radius: 10px;
        color: #fff;
        font-weight: 900;
        padding: 10px 16px;
    }

    .btn-main:hover {
        filter: brightness(1.07);
        color: #fff;
    }

    .btn-toggle {
        background: rgba(56, 189, 248, 0.12);
        border: 1px solid rgba(56, 189, 248, 0.36);
        color: #dff7ff;
        border-radius: 10px;
        font-weight: 800;
        padding: 6px 10px;
    }

    .btn-toggle:hover {
        background: rgba(56, 189, 248, 0.22);
        color: #ffffff;
    }

    .btn-delete {
        background: rgba(244, 63, 94, 0.14);
        border: 1px solid rgba(244, 63, 94, 0.38);
        color: #fecaca;
        border-radius: 10px;
        font-weight: 800;
        padding: 6px 10px;
    }

    .btn-delete:hover {
        background: rgba(244, 63, 94, 0.26);
        color: #ffffff;
    }

    .table {
        color: #fff !important;
    }

    .table th {
        background: rgba(8, 20, 48, .58) !important;
        color: #fff !important;
        border-color: rgba(96, 165, 250, .22) !important;
        white-space: nowrap;
    }

    .table td {
        background: rgba(8, 20, 48, .18) !important;
        color: #d7e7ff !important;
        border-color: rgba(96, 165, 250, .20) !important;
        vertical-align: middle;
    }

    .table strong {
        color: #ffffff !important;
    }

    .badge {
        border-radius: 999px;
        font-weight: 900;
        padding: 6px 10px;
    }

    .badge-priority-info {
        background: rgba(56, 189, 248, .18);
        color: #dff7ff;
        border: 1px solid rgba(56, 189, 248, .34);
    }

    .badge-priority-success {
        background: rgba(34, 197, 94, .18);
        color: #bbf7d0;
        border: 1px solid rgba(34, 197, 94, .34);
    }

    .badge-priority-warning {
        background: rgba(250, 204, 21, .18);
        color: #fef3c7;
        border: 1px solid rgba(250, 204, 21, .34);
    }

    .badge-priority-danger {
        background: rgba(244, 63, 94, .18);
        color: #fecaca;
        border: 1px solid rgba(244, 63, 94, .34);
    }

    .team-warning {
        background: rgba(250, 204, 21, .12);
        border: 1px solid rgba(250, 204, 21, .35);
        color: #fde68a;
        border-radius: 14px;
        padding: 12px;
        font-weight: 700;
    }

    .action-stack {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        align-items: center;
    }

    .action-stack form {
        margin: 0;
    }

    @media (max-width: 768px) {
        .action-stack {
            display: grid;
        }
    }
</style>

<div class="announcement-shell">
    <div class="ann-card">
        <h2>
            <i class="fas fa-bullhorn me-2"></i>
            CSR Manager Announcements
        </h2>

        <p class="text-muted mb-0">
            Create announcements that pop up for regular CSRs under your team.
        </p>
    </div>

    <?php if($message): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle me-2"></i>
            <?= h($message) ?>
        </div>
    <?php endif; ?>

    <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?= h($error) ?>
        </div>
    <?php endif; ?>

    <?php if(!$managerTeams): ?>
        <div class="team-warning">
            <i class="fas fa-triangle-exclamation me-2"></i>
            You do not have an active team yet. Announcements need a team target, so ask the admin to create a team for this manager and assign regular CSRs under it.
        </div>
    <?php endif; ?>

    <div class="ann-card">
        <h4>Create Announcement</h4>

        <form method="POST" class="row g-3">
            <div class="<?= $singleTeam ? 'col-md-6' : 'col-md-5' ?>">
                <label class="form-label">Title</label>
                <input 
                    class="form-control" 
                    name="title" 
                    placeholder="Enter announcement title"
                    required
                >
            </div>

            <?php if($singleTeam): ?>
                <div class="col-md-3">
                    <label class="form-label">Team</label>

                    <div class="team-target-box">
                        <i class="fas fa-users me-2"></i>
                        <?= h($singleTeam['team_name']) ?>
                    </div>

                    <input 
                        type="hidden" 
                        name="team_id" 
                        value="<?= (int)$singleTeam['id'] ?>"
                    >
                </div>
            <?php else: ?>
                <div class="col-md-3">
                    <label class="form-label">Team</label>

                    <select class="form-select" name="team_id" required>
                        <option value="">Select Team</option>

                        <?php foreach($managerTeams as $team): ?>
                            <option value="<?= (int)$team['id'] ?>">
                                <?= h($team['team_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            <?php endif; ?>

            <div class="col-md-2">
                <label class="form-label">Priority</label>

                <select class="form-select" name="priority">
                    <option value="info">Info</option>
                    <option value="success">Success</option>
                    <option value="warning">Warning</option>
                    <option value="danger">Urgent</option>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Expires At</label>
                <input class="form-control" type="datetime-local" name="expires_at">
            </div>

            <div class="col-12">
                <label class="form-label">Message</label>

                <textarea 
                    class="form-control" 
                    name="message" 
                    rows="4" 
                    placeholder="Write your announcement message here..."
                    required
                ></textarea>
            </div>

            <div class="col-12">
                <button 
                    class="btn-main" 
                    name="create_announcement" 
                    <?= !$managerTeams ? 'disabled' : '' ?>
                >
                    <i class="fas fa-paper-plane me-1"></i>
                    Post Announcement
                </button>
            </div>
        </form>
    </div>

    <div class="ann-card">
        <h4>Announcement History</h4>

        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Team</th>
                        <th>Priority</th>
                        <th>Status</th>
                        <th>Expires</th>
                        <th>Created</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach($ann as $a): ?>
                        <?php
                            $priorityClass = 'badge-priority-info';

                            if ($a['priority'] === 'success') {
                                $priorityClass = 'badge-priority-success';
                            } elseif ($a['priority'] === 'warning') {
                                $priorityClass = 'badge-priority-warning';
                            } elseif ($a['priority'] === 'danger') {
                                $priorityClass = 'badge-priority-danger';
                            }
                        ?>

                        <tr>
                            <td>
                                <strong><?= h($a['title']) ?></strong><br>
                                <small class="text-muted">
                                    <?= h(shortAnnouncementText($a['message'], 90)) ?>
                                </small>
                            </td>

                            <td><?= h($a['team_name'] ?: 'Manager Team') ?></td>

                            <td>
                                <span class="badge <?= $priorityClass ?>">
                                    <?= h(ucfirst($a['priority'])) ?>
                                </span>
                            </td>

                            <td>
                                <?= $a['is_active']
                                    ? '<span class="badge bg-success">Active</span>'
                                    : '<span class="badge bg-secondary">Inactive</span>'
                                ?>
                            </td>

                            <td>
                                <?= !empty($a['expires_at'])
                                    ? h(date('M d, Y h:i A', strtotime($a['expires_at'])))
                                    : '<span class="text-muted">No expiry</span>'
                                ?>
                            </td>

                            <td>
                                <?= h(date('M d, Y h:i A', strtotime($a['created_at']))) ?>
                            </td>

                            <td>
                                <div class="action-stack">
                                    <form method="POST">
                                        <input 
                                            type="hidden" 
                                            name="announcement_id" 
                                            value="<?= (int)$a['id'] ?>"
                                        >

                                        <button 
                                            class="btn-toggle" 
                                            name="toggle_announcement"
                                        >
                                            <i class="fas fa-toggle-on me-1"></i>
                                            Toggle
                                        </button>
                                    </form>

                                    <form 
                                        method="POST" 
                                        onsubmit="return confirm('Delete this announcement permanently? This cannot be undone.');"
                                    >
                                        <input 
                                            type="hidden" 
                                            name="announcement_id" 
                                            value="<?= (int)$a['id'] ?>"
                                        >

                                        <button 
                                            class="btn-delete" 
                                            name="delete_announcement"
                                        >
                                            <i class="fas fa-trash me-1"></i>
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if(empty($ann)): ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">
                                No announcements yet.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php
$content = ob_get_clean();
include 'layout.php';