<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/integrated-admin-auth.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 || !isset($adminData['admin_type']) || $adminData['admin_type'] !== 'master') {
    if (!$adminData) {
        session_destroy();
        header('Location: login.php');
    } else {
        header('Location: login.php?error=insufficient_permissions');
    }
    exit;
}

// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'linkslot88_autopred97841dellon9781a');
define('DB_PASS', 'prediksiautomanjur9854ikjbnienfxx');
define('DB_NAME', 'linkslot88_autoprediksikjmngpfjr941');

// Get admin info from validated session
$currentSite = $adminData['site_access'] ?? 'master';
$isMasterAdmin = ($adminData['admin_type'] === 'master');

// Only allow access for Master Admin (already verified above, but double-check)
if (!$isMasterAdmin) {
    header('Location: dashboard.php');
    exit;
}

$title = "Master Support Tickets";
$currentPage = "master-support";

// Get sites data for filtering
$sites = [
    'mayortogel' => 'MayorTogel',
    'wajahtoto' => 'WajahToto', 
    'yuki585' => 'Yuki585'
];

// Handle form submission (reply to ticket)
$message = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    if ($action === 'reply') {
        $ticket_id = (int)$_POST['ticket_id'];
        $site_code = $_POST['site_code'];
        $reply_message = trim($_POST['reply_message']);
        $update_status = $_POST['update_status'];
        
        if (!empty($reply_message) && !empty($site_code)) {
            try {
                $pdo = new PDO(
                    "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                    DB_USER,
                    DB_PASS,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // Insert reply
                $reply_sql = "INSERT INTO support_responses_{$site_code} (ticket_id, admin_name, response, created_at) VALUES (?, ?, ?, NOW())";
                $reply_stmt = $pdo->prepare($reply_sql);
                $reply_stmt->execute([$ticket_id, 'Master Admin', $reply_message]);
                
                // Update ticket status if specified
                if (!empty($update_status)) {
                    $update_sql = "UPDATE support_tickets_{$site_code} SET status = ?, updated_at = NOW() WHERE id = ?";
                    $update_stmt = $pdo->prepare($update_sql);
                    $update_stmt->execute([$update_status, $ticket_id]);
                }
                
                $success = true;
                $message = "Balasan berhasil dikirim ke tiket #{$ticket_id} dari {$sites[$site_code]}.";
                
            } catch (Exception $e) {
                $message = "Error: " . $e->getMessage();
            }
        } else {
            $message = "Mohon isi pesan balasan.";
        }
    }
    
    if ($action === 'bulk_status') {
        $ticket_ids = $_POST['ticket_ids'] ?? [];
        $new_status = $_POST['bulk_status'];
        
        if (!empty($ticket_ids) && !empty($new_status)) {
            $updated_count = 0;
            
            foreach ($ticket_ids as $ticket_data) {
                list($site_code, $ticket_id) = explode(':', $ticket_data);
                
                try {
                    $pdo = new PDO(
                        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                        DB_USER,
                        DB_PASS,
                        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                    );
                    
                    $update_sql = "UPDATE support_tickets_{$site_code} SET status = ?, updated_at = NOW() WHERE id = ?";
                    $update_stmt = $pdo->prepare($update_sql);
                    $update_stmt->execute([$new_status, $ticket_id]);
                    $updated_count++;
                    
                } catch (Exception $e) {
                    // Continue with other tickets
                }
            }
            
            $success = true;
            $message = "Berhasil update status $updated_count tiket.";
        }
    }
}

// Pagination and filtering
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;
$filter_site = $_GET['site'] ?? '';
$filter_status = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Get all tickets from all sites
$all_tickets = [];
$total_tickets = 0;

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    
    foreach ($sites as $site_code => $site_name) {
        // Skip if filtering by specific site
        if (!empty($filter_site) && $filter_site !== $site_code) {
            continue;
        }
        
        $where_conditions = [];
        $params = [];
        
        if (!empty($filter_status)) {
            $where_conditions[] = "status = ?";
            $params[] = $filter_status;
        }
        
        if (!empty($search)) {
            $where_conditions[] = "(username LIKE ? OR whatsapp LIKE ? OR subject LIKE ? OR complaint LIKE ?)";
            $search_param = "%{$search}%";
            $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
        }
        
        $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
        
        try {
            // Get tickets for this site
            $sql = "SELECT *, '{$site_code}' as site_code, '{$site_name}' as site_name 
                    FROM support_tickets_{$site_code} 
                    {$where_clause} 
                    ORDER BY created_at DESC";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $site_tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $all_tickets = array_merge($all_tickets, $site_tickets);
            
        } catch (Exception $e) {
            // Table might not exist, skip this site
            continue;
        }
    }
    
    // Sort all tickets by creation date
    usort($all_tickets, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    $total_tickets = count($all_tickets);
    
    // Apply pagination
    $all_tickets = array_slice($all_tickets, $offset, $limit);
    
} catch (Exception $e) {
    $message = "Error loading tickets: " . $e->getMessage();
}

// Calculate pagination
$total_pages = ceil($total_tickets / $limit);

// Page-specific variables for master header
$pageTitle = $pageTitle ?? 'Master Admin Panel';
$pageDescription = $pageDescription ?? 'Master admin functionality';

// Include master admin header
include 'admin-sidebar-template.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="mb-0"><i class="bi bi-headset me-2"></i>Master Support Tickets</h4>
                    <small class="text-muted">Kelola tiket dari semua situs</small>
                </div>
                
                <div class="card-body">
                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $success ? 'success' : 'danger'; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Filters -->
                    <form method="GET" class="row g-3 mb-4">
                        <div class="col-md-3">
                            <label class="form-label">Filter Situs</label>
                            <select name="site" class="form-control">
                                <option value="">Semua Situs</option>
                                <?php foreach ($sites as $code => $name): ?>
                                <option value="<?php echo $code; ?>" <?php echo $filter_site === $code ? 'selected' : ''; ?>>
                                    <?php echo $name; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label class="form-label">Filter Status</label>
                            <select name="status" class="form-control">
                                <option value="">Semua Status</option>
                                <option value="open" <?php echo $filter_status === 'open' ? 'selected' : ''; ?>>Open</option>
                                <option value="in_progress" <?php echo $filter_status === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                                <option value="resolved" <?php echo $filter_status === 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                                <option value="closed" <?php echo $filter_status === 'closed' ? 'selected' : ''; ?>>Closed</option>
                            </select>
                        </div>
                        
                        <div class="col-md-4">
                            <label class="form-label">Pencarian</label>
                            <input type="text" name="search" class="form-control" value="<?php echo htmlspecialchars($search); ?>" placeholder="Cari username, whatsapp, subjek...">
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary d-block w-100">
                                <i class="bi bi-search"></i> Filter
                            </button>
                        </div>
                    </form>

                    <!-- Bulk Actions -->
                    <?php if (!empty($all_tickets)): ?>
                    <form method="POST" id="bulkForm" class="mb-3">
                        <input type="hidden" name="action" value="bulk_status">
                        <div class="row g-2">
                            <div class="col-md-3">
                                <select name="bulk_status" class="form-control" required>
                                    <option value="">Pilih Status Baru</option>
                                    <option value="open">Open</option>
                                    <option value="in_progress">In Progress</option>
                                    <option value="resolved">Resolved</option>
                                    <option value="closed">Closed</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <button type="submit" class="btn btn-warning" onclick="return confirm('Update status tiket terpilih?')">
                                    <i class="bi bi-arrow-repeat"></i> Update Status
                                </button>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">Pilih tiket dengan checkbox untuk update massal</small>
                            </div>
                        </div>
                    </form>
                    <?php endif; ?>

                    <!-- Tickets Table -->
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th width="30">
                                        <input type="checkbox" id="selectAll">
                                    </th>
                                    <th>ID</th>
                                    <th>Situs</th>
                                    <th>Pengirim</th>
                                    <th>Subjek</th>
                                    <th>Status</th>
                                    <th>Tanggal</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($all_tickets)): ?>
                                <?php foreach ($all_tickets as $ticket): ?>
                                <tr>
                                    <td>
                                        <input type="checkbox" name="ticket_ids[]" value="<?php echo $ticket['site_code'] . ':' . $ticket['id']; ?>" form="bulkForm">
                                    </td>
                                    <td><span class="badge bg-secondary">#<?php echo $ticket['id']; ?></span></td>
                                    <td><span class="badge bg-info"><?php echo $ticket['site_name']; ?></span></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($ticket['username']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($ticket['whatsapp']); ?></small>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($ticket['subject']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars(substr($ticket['complaint'], 0, 100)); ?>...</small>
                                    </td>
                                    <td>
                                        <?php
                                        $status_class = [
                                            'open' => 'bg-danger',
                                            'in_progress' => 'bg-warning',
                                            'resolved' => 'bg-success',
                                            'closed' => 'bg-secondary'
                                        ];
                                        $status_text = [
                                            'open' => 'Open',
                                            'in_progress' => 'In Progress',
                                            'resolved' => 'Resolved',
                                            'closed' => 'Closed'
                                        ];
                                        ?>
                                        <span class="badge <?php echo $status_class[$ticket['status']] ?? 'bg-secondary'; ?>">
                                            <?php echo $status_text[$ticket['status']] ?? $ticket['status']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small>
                                            <?php echo date('d M Y H:i', strtotime($ticket['created_at'])); ?>
                                        </small>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary" 
                                                onclick="viewTicket(<?php echo $ticket['id']; ?>, '<?php echo $ticket['site_code']; ?>')"
                                                data-bs-toggle="modal" data-bs-target="#ticketModal">
                                            <i class="bi bi-eye"></i> Lihat
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">
                                        <i class="bi bi-inbox"></i><br>
                                        Tidak ada tiket ditemukan
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&site=<?php echo $filter_site; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>">Previous</a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&site=<?php echo $filter_site; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&site=<?php echo $filter_site; ?>&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>">Next</a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    
                    <div class="text-center">
                        <small class="text-muted">
                            Menampilkan <?php echo count($all_tickets); ?> dari <?php echo $total_tickets; ?> total tiket
                        </small>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </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">Detail Tiket</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="ticketContent">
                    <div class="text-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Select all checkbox functionality
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('input[name="ticket_ids[]"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// View ticket function
async function viewTicket(ticketId, siteCode) {
    document.getElementById('ticketContent').innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
    `;
    
    try {
        const response = await fetch('get-ticket-details.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `ticket_id=${ticketId}&site_code=${siteCode}`
        });
        
        const data = await response.text();
        document.getElementById('ticketContent').innerHTML = data;
    } catch (error) {
        document.getElementById('ticketContent').innerHTML = `
            <div class="alert alert-danger">
                Error loading ticket details: ${error.message}
            </div>
        `;
    }
}
</script>

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