<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/integrated-admin-auth.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    http_response_code(403);
    echo '<div class="alert alert-danger">Access denied - Not logged in</div>';
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData || !isset($adminData['admin_type']) || $adminData['admin_type'] !== 'master') {
    http_response_code(403);
    echo '<div class="alert alert-danger">Access denied - Insufficient permissions</div>';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo '<div class="alert alert-danger">Method not allowed</div>';
    exit;
}

$ticket_id = (int)$_POST['ticket_id'];
$site_code = $_POST['site_code'];

$sites = [
    'mayortogel' => 'MayorTogel',
    'wajahtoto' => 'WajahToto', 
    'yuki585' => 'Yuki585'
];

if (!isset($sites[$site_code])) {
    echo '<div class="alert alert-danger">Invalid site code</div>';
    exit;
}

// Database configuration
if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
if (!defined('DB_USER')) define('DB_USER', 'root');
if (!defined('DB_PASS')) define('DB_PASS', '');

try {
    $pdo = (new Database())->getConnection();
    
    // Get ticket details
    $ticket_sql = "SELECT * FROM support_tickets_{$site_code} WHERE id = ?";
    $ticket_stmt = $pdo->prepare($ticket_sql);
    $ticket_stmt->execute([$ticket_id]);
    $ticket = $ticket_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        echo '<div class="alert alert-danger">Tiket tidak ditemukan</div>';
        exit;
    }
    
    // Get replies
    $replies_sql = "SELECT * FROM support_responses_{$site_code} WHERE ticket_id = ? ORDER BY created_at ASC";
    $replies_stmt = $pdo->prepare($replies_sql);
    $replies_stmt->execute([$ticket_id]);
    $replies = $replies_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $status_class = [
        'open' => 'bg-danger',
        'in_progress' => 'bg-warning text-dark',
        'resolved' => 'bg-success',
        'closed' => 'bg-secondary'
    ];
    $status_text = [
        'open' => 'Open',
        'in_progress' => 'In Progress',
        'resolved' => 'Resolved',
        'closed' => 'Closed'
    ];
    
    ?>
    
    <!-- Ticket Header -->
    <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
            <h6>Tiket #<?php echo $ticket['id']; ?> - <?php echo $sites[$site_code]; ?></h6>
            <span class="badge <?php echo $status_class[$ticket['status']] ?? 'bg-secondary'; ?>">
                <?php echo $status_text[$ticket['status']] ?? $ticket['status']; ?>
            </span>
        </div>
        <small class="text-muted">
            <?php echo date('d M Y H:i', strtotime($ticket['created_at'])); ?>
        </small>
    </div>
    
    <!-- Original Message -->
    <div class="card mb-3">
        <div class="card-header">
            <strong><?php echo htmlspecialchars($ticket['username']); ?></strong>
            <small class="text-muted">WhatsApp: <?php echo htmlspecialchars($ticket['whatsapp']); ?></small>
        </div>
        <div class="card-body">
            <h6><?php echo htmlspecialchars($ticket['subject']); ?></h6>
            <p><?php echo nl2br(htmlspecialchars($ticket['complaint'])); ?></p>
        </div>
    </div>
    
    <!-- Replies -->
    <?php if (!empty($replies)): ?>
    <div class="mb-3">
        <h6>Balasan:</h6>
        <?php foreach ($replies as $reply): ?>
        <div class="card mb-2">
            <div class="card-body py-2">
                <div class="d-flex justify-content-between">
                    <strong><?php echo htmlspecialchars($reply['admin_name']); ?></strong>
                    <small class="text-muted"><?php echo date('d M Y H:i', strtotime($reply['created_at'])); ?></small>
                </div>
                <p class="mb-1"><?php echo nl2br(htmlspecialchars($reply['response'])); ?></p>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    
    <!-- Reply Form -->
    <form method="POST" action="master-support.php">
        <input type="hidden" name="action" value="reply">
        <input type="hidden" name="ticket_id" value="<?php echo $ticket['id']; ?>">
        <input type="hidden" name="site_code" value="<?php echo $site_code; ?>">
        
        <div class="mb-3">
            <label class="form-label">Balasan:</label>
            <textarea name="reply_message" class="form-control" rows="4" required placeholder="Tulis balasan..."></textarea>
        </div>
        
        <div class="mb-3">
            <label class="form-label">Update Status:</label>
            <select name="update_status" class="form-control">
                <option value="">Tidak berubah</option>
                <option value="in_progress" <?php echo $ticket['status'] === 'open' ? 'selected' : ''; ?>>In Progress</option>
                <option value="resolved">Resolved</option>
                <option value="closed">Closed</option>
            </select>
        </div>
        
        <div class="d-flex justify-content-end">
            <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Tutup</button>
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-reply"></i> Kirim Balasan
            </button>
        </div>
    </form>
    
    <?php
    
} catch (Exception $e) {
    echo '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>