<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

// Check permissions
$permissionMiddleware = new PermissionMiddleware($integratedAuth, $adminData);
if (!$permissionMiddleware->hasPermission('manage_support')) {
    header('Location: dashboard.php?error=' . urlencode('Access denied.'));
    exit;
}

$db = new Database();
$pdo = $db->getConnection();
$message = '';
$messageType = '';

// Handle ticket actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'respond_ticket':
                    $ticketId = (int)$_POST['ticket_id'];
                    $response = trim($_POST['response']);
                    $adminName = $adminData['username'] ?? 'Admin';
                    
                    if (empty($response)) {
                        throw new Exception('Response tidak boleh kosong!');
                    }
                    
                    // Insert response
                    $stmt = $pdo->prepare("INSERT INTO support_responses (ticket_id, admin_name, response, is_admin) VALUES (?, ?, ?, 1)");
                    $stmt->execute([$ticketId, $adminName, $response]);
                    
                    // Update ticket status
                    $stmt = $pdo->prepare("UPDATE support_tickets SET status = 'answered', updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$ticketId]);
                    
                    $message = 'Response berhasil dikirim!';
                    $messageType = 'success';
                    break;
                    
                case 'close_ticket':
                    $ticketId = (int)$_POST['ticket_id'];
                    
                    $stmt = $pdo->prepare("UPDATE support_tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$ticketId]);
                    
                    $message = 'Ticket berhasil ditutup!';
                    $messageType = 'success';
                    break;
                    
                case 'reopen_ticket':
                    $ticketId = (int)$_POST['ticket_id'];
                    
                    $stmt = $pdo->prepare("UPDATE support_tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$ticketId]);
                    
                    $message = 'Ticket berhasil dibuka kembali!';
                    $messageType = 'success';
                    break;
            }
        }
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Get filter parameters
$statusFilter = $_GET['status'] ?? 'all';
$searchQuery = trim($_GET['search'] ?? '');

// Build query
$whereConditions = [];
$params = [];

if ($statusFilter !== 'all') {
    $whereConditions[] = "st.status = ?";
    $params[] = $statusFilter;
}

if (!empty($searchQuery)) {
    $whereConditions[] = "(st.ticket_number LIKE ? OR st.username LIKE ? OR st.subject LIKE ?)";
    $searchTerm = "%$searchQuery%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);

// Get tickets with latest response
$sql = "SELECT st.*, 
               (SELECT sr.response FROM support_responses sr WHERE sr.ticket_id = st.id ORDER BY sr.created_at DESC LIMIT 1) as latest_response,
               (SELECT COUNT(*) FROM support_responses sr WHERE sr.ticket_id = st.id) as response_count
        FROM support_tickets st 
        $whereClause
        ORDER BY st.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM support_tickets")->fetchColumn(),
    'open' => $pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'open'")->fetchColumn(),
    'answered' => $pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'answered'")->fetchColumn(),
    'closed' => $pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'closed'")->fetchColumn()
];

$pageTitle = 'Support Tickets';
include 'admin-sidebar-template.php';
?>

<div class="content-body">
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
            <i class="bi bi-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Total Tickets</h6>
                            <h3 class="mb-0"><?php echo $stats['total']; ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-ticket-perforated fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Open</h6>
                            <h3 class="mb-0"><?php echo $stats['open']; ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-exclamation-circle fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Answered</h6>
                            <h3 class="mb-0"><?php echo $stats['answered']; ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-reply fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Closed</h6>
                            <h3 class="mb-0"><?php echo $stats['closed']; ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-check-circle fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Status Filter</label>
                    <select name="status" class="form-select">
                        <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>Semua Status</option>
                        <option value="open" <?php echo $statusFilter === 'open' ? 'selected' : ''; ?>>Open</option>
                        <option value="answered" <?php echo $statusFilter === 'answered' ? 'selected' : ''; ?>>Answered</option>
                        <option value="closed" <?php echo $statusFilter === 'closed' ? 'selected' : ''; ?>>Closed</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" 
                           value="<?php echo htmlspecialchars($searchQuery); ?>"
                           placeholder="Cari berdasarkan ticket number, username, atau subject...">
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="bi bi-search"></i> Filter
                    </button>
                    <a href="support.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-clockwise"></i> Reset
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Tickets List -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="bi bi-list-ul"></i>
                Support Tickets (<?php echo count($tickets); ?>)
            </h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($tickets)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-inbox fs-1 text-muted"></i>
                    <h5 class="mt-3 text-muted">Tidak ada ticket ditemukan</h5>
                    <p class="text-muted">Belum ada ticket support yang masuk atau sesuai dengan filter yang dipilih.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Ticket #</th>
                                <th>User</th>
                                <th>Subject</th>
                                <th>Status</th>
                                <th>Responses</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($tickets as $ticket): ?>
                            <tr>
                                <td>
                                    <code><?php echo htmlspecialchars($ticket['ticket_number']); ?></code>
                                </td>
                                <td>
                                    <div>
                                        <strong><?php echo htmlspecialchars($ticket['username']); ?></strong>
                                        <br>
                                        <small class="text-muted">
                                            <i class="bi bi-whatsapp"></i>
                                            <?php echo htmlspecialchars($ticket['whatsapp']); ?>
                                        </small>
                                    </div>
                                </td>
                                <td>
                                    <div>
                                        <strong><?php echo htmlspecialchars($ticket['subject']); ?></strong>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo substr(htmlspecialchars($ticket['complaint']), 0, 100); ?>...
                                        </small>
                                    </div>
                                </td>
                                <td>
                                    <?php
                                    $statusClasses = [
                                        'open' => 'bg-warning text-dark',
                                        'answered' => 'bg-info text-white',
                                        'closed' => 'bg-success text-white'
                                    ];
                                    $statusClass = $statusClasses[$ticket['status']] ?? 'bg-secondary';
                                    ?>
                                    <span class="badge <?php echo $statusClass; ?>">
                                        <?php echo ucfirst($ticket['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-primary">
                                        <?php echo $ticket['response_count']; ?> responses
                                    </span>
                                </td>
                                <td>
                                    <small>
                                        <?php echo date('d/m/Y H:i', strtotime($ticket['created_at'])); ?>
                                    </small>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-outline-primary" 
                                                onclick="viewTicket(<?php echo $ticket['id']; ?>)">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                        <?php if ($ticket['status'] !== 'closed'): ?>
                                        <button type="button" class="btn btn-outline-success" 
                                                onclick="respondTicket(<?php echo $ticket['id']; ?>)">
                                            <i class="bi bi-reply"></i>
                                        </button>
                                        <button type="button" class="btn btn-outline-danger" 
                                                onclick="closeTicket(<?php echo $ticket['id']; ?>)">
                                            <i class="bi bi-x-circle"></i>
                                        </button>
                                        <?php else: ?>
                                        <button type="button" class="btn btn-outline-warning" 
                                                onclick="reopenTicket(<?php echo $ticket['id']; ?>)">
                                            <i class="bi bi-arrow-clockwise"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Ticket Detail Modal -->
<div class="modal fade" id="ticketModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Ticket Detail</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="ticketModalBody">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<!-- Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Balas Ticket</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="respond_ticket">
                    <input type="hidden" name="ticket_id" id="responseTicketId">
                    
                    <div class="mb-3">
                        <label class="form-label">Response</label>
                        <textarea name="response" class="form-control" rows="5" required
                                  placeholder="Tulis response untuk user..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Kirim Response</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function viewTicket(ticketId) {
    fetch(`../api/get-ticket-detail.php?id=${ticketId}`)
        .then(response => response.text())
        .then(data => {
            document.getElementById('ticketModalBody').innerHTML = data;
            new bootstrap.Modal(document.getElementById('ticketModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading ticket detail');
        });
}

function respondTicket(ticketId) {
    document.getElementById('responseTicketId').value = ticketId;
    new bootstrap.Modal(document.getElementById('responseModal')).show();
}

function closeTicket(ticketId) {
    if (confirm('Apakah Anda yakin ingin menutup ticket ini?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="close_ticket">
            <input type="hidden" name="ticket_id" value="${ticketId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

function reopenTicket(ticketId) {
    if (confirm('Apakah Anda yakin ingin membuka kembali ticket ini?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="reopen_ticket">
            <input type="hidden" name="ticket_id" value="${ticketId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<?php include 'admin-sidebar-footer.php'; ?>