<?php
/**
 * ticket_logic.php - টিকিট ম্যানেজমেন্টের লজিক এবং ভিউ পার্ট (With Dashboard, Reverse Serial, Count & Filter)
 */

// ১. টিকিট আপডেট করার লজিক (Action Handling)
if (isset($_POST['update_ticket'])) {
    $t_id = mysqli_real_escape_string($conn, $_POST['ticket_id']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $reply = mysqli_real_escape_string($conn, $_POST['admin_reply']);
    $staff = mysqli_real_escape_string($conn, $_POST['assigned_staff']); 
    $logged_admin = $_SESSION['admin_user'] ?? 'Admin';
    $current_time = date('Y-m-d H:i:s');
    
    $old_res = mysqli_query($conn, "SELECT status, assigned_staff FROM tickets WHERE id=$t_id");
    $old_data = mysqli_fetch_assoc($old_res);
    
    $update_fields = [
        "status='$status'",
        "admin_reply='$reply'",
        "assigned_staff='$staff'"
    ];

    if ($staff != '' && $old_data['assigned_staff'] != $staff) {
        $update_fields[] = "assigned_by='$logged_admin'";
        $update_fields[] = "assigned_at='$current_time'";
    }

    if ($status == 'Resolved' && $old_data['status'] != 'Resolved') {
        $update_fields[] = "resolved_at='$current_time'";
    }

    $query = "UPDATE tickets SET " . implode(', ', $update_fields) . " WHERE id=$t_id";
    
    if(mysqli_query($conn, $query)) {
        echo "<script>window.location.href='admin.php?view=tickets';</script>";
        exit();
    }
}

// ২. ড্যাসবোর্ড ডাটা ক্যালকুলেশন (চিত্র অনুযায়ী)
$count_pending = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM tickets WHERE status='Pending'"))['total'];
$count_progress = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM tickets WHERE status='In Progress'"))['total'];
$count_resolved = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM tickets WHERE status='Resolved'"))['total'];

// ৩. সার্চ এবং ফিল্টার লজিক
$search_query = "";
$where_clauses = [];

if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = mysqli_real_escape_string($conn, $_GET['search']);
    $where_clauses[] = "(customer_id LIKE '%$search%' OR phone_number LIKE '%$search%')";
}

if (isset($_GET['filter_status']) && !empty($_GET['filter_status'])) {
    $f_status = mysqli_real_escape_string($conn, $_GET['filter_status']);
    $where_clauses[] = "status = '$f_status'";
}

$where_sql = "";
if (count($where_clauses) > 0) {
    $where_sql = " WHERE " . implode(' AND ', $where_clauses);
}

// ডাটা সংগ্রহ
$tickets = mysqli_query($conn, "SELECT * FROM tickets $where_sql ORDER BY id DESC");
$total_tickets_count = mysqli_num_rows($tickets); 
$staff_db_res = mysqli_query($conn, "SELECT staff_name FROM staff ORDER BY staff_name ASC");

// উল্টো দিক থেকে ক্রমিক নম্বর শুরু করার জন্য ভেরিয়েবল
$serial_no = $total_tickets_count;
?>

<!-- ড্যাসবোর্ড ডিজাইন (চিত্র অনুযায়ী নতুন সেকশন) -->
<style>
    .support-dashboard { display: flex; gap: 20px; margin-bottom: 25px; flex-wrap: wrap; }
    .stat-card { background: white; padding: 20px; border-radius: 12px; flex: 1; min-width: 200px; display: flex; align-items: center; gap: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border-bottom: 4px solid #ddd; }
    .stat-icon { width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; }
    .bg-pending-light { background: #ffe9e9; color: #f44336; }
    .bg-progress-light { background: #fff4e5; color: #ff9800; }
    .bg-resolved-light { background: #e8f5e9; color: #4caf50; }
    .stat-info h2 { margin: 0; font-size: 24px; color: #333; }
    .stat-info p { margin: 0; color: #777; font-size: 14px; font-weight: 500; }
    .border-pending { border-color: #f44336; }
    .border-progress { border-color: #ff9800; }
    .border-resolved { border-color: #4caf50; }
</style>

<div class="support-dashboard">
    <div class="stat-card border-pending">
        <div class="stat-icon bg-pending-light"><i class="fas fa-exclamation-circle"></i></div>
        <div class="stat-info">
            <h2><?php echo $count_pending; ?></h2>
            <p>পেন্ডিং টিকিট</p>
        </div>
    </div>
    <div class="stat-card border-progress">
        <div class="stat-icon bg-progress-light"><i class="fas fa-spinner fa-spin"></i></div>
        <div class="stat-info">
            <h2><?php echo $count_progress; ?></h2>
            <p>চলমান (Progress)</p>
        </div>
    </div>
    <div class="stat-card border-resolved">
        <div class="stat-icon bg-resolved-light"><i class="fas fa-check-double"></i></div>
        <div class="stat-info">
            <h2><?php echo $count_resolved; ?></h2>
            <p>সল্ভড টিকিট</p>
        </div>
    </div>
</div>

<!-- ৩. টিকিটের টেবিল ডিজাইন (UI Part) -->
<div id="tickets" class="section-card">
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
        <h3 style="margin: 0;">
            <i class="fas fa-headset"></i> কাস্টমার সাপোর্ট টিকিট ট্র্যাকিং 
            <span style="background: var(--primary); color: white; padding: 2px 10px; border-radius: 20px; font-size: 14px; margin-left: 10px; vertical-align: middle;">
                <?php echo $total_tickets_count; ?>
            </span>
        </h3>
        
        <!-- সার্চ এবং ফিল্টার ফর্ম -->
        <form action="admin.php" method="GET" style="display: flex; gap: 10px; align-items: center;">
            <input type="hidden" name="view" value="tickets">
            <input type="text" name="search" placeholder="আইডি বা ফোন নম্বর..." value="<?php echo $_GET['search'] ?? ''; ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 5px; outline: none;">
            
            <select name="filter_status" style="padding: 8px; border: 1px solid #ddd; border-radius: 5px; outline: none;">
                <option value="">সব স্ট্যাটাস</option>
                <option value="Pending" <?php echo ($_GET['filter_status'] ?? '') == 'Pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="In Progress" <?php echo ($_GET['filter_status'] ?? '') == 'In Progress' ? 'selected' : ''; ?>>In Progress</option>
                <option value="Resolved" <?php echo ($_GET['filter_status'] ?? '') == 'Resolved' ? 'selected' : ''; ?>>Resolved</option>
            </select>
            
            <button type="submit" class="btn btn-primary" style="padding: 8px 15px;"><i class="fas fa-search"></i></button>
            <?php if(isset($_GET['search']) || isset($_GET['filter_status'])): ?>
                <a href="admin.php?view=tickets" class="btn" style="background:#eee; color:#666; padding: 8px 15px;"><i class="fas fa-times"></i></a>
            <?php endif; ?>
        </form>
    </div>

    <table>
        <thead>
            <tr><th>SL</th> <th>ইউজার ও সময়</th> <th>সমস্যা ও অ্যাসাইনমেন্ট</th> <th>স্ট্যাটাস</th> <th>অ্যাকশন</th></tr>
        </thead>
        <tbody>
            <?php if($tickets && $total_tickets_count > 0): ?>
                <?php while($t = mysqli_fetch_assoc($tickets)): ?>
                <tr>
                    <td style="font-weight: bold; color: #555;">#<?php echo $serial_no--; ?></td>
                    <td>
                        <strong><?php echo htmlspecialchars($t['customer_id'] ?? 'N/A'); ?></strong><br>
                        <small style="color:#888;">ফোন: <?php echo $t['phone_number']; ?></small><br>
                        <span style="font-size:10px; color:#999; display:block; margin-top:2px;">তৈরি: <?php echo date('d-m-Y h:i A', strtotime($t['created_at'])); ?></span>
                        <small style="color: #bbb; font-size: 9px;">Original ID: <?php echo $t['id']; ?></small>
                    </td>
                    <td>
                        <div style="margin-bottom: 5px; color: #333; font-weight: 500;">
                            <?php echo htmlspecialchars($t['issue_type'] ?? 'N/A'); ?>
                        </div>
                        
                        <?php if(!empty($t['assigned_staff'])): ?>
                            <div style="font-size: 11px; background: #f0f7ff; padding: 5px; border-radius: 4px; border-left: 3px solid var(--primary);">
                                <i class="fas fa-user-tag"></i> <strong><?php echo htmlspecialchars($t['assigned_staff']); ?></strong> (এসাইনড)<br>
                                <small>বাই: <?php echo htmlspecialchars($t['assigned_by'] ?? 'System'); ?></small>
                                <span style="font-size:9px; color:#777; display:block;">সময়: <?php echo !empty($t['assigned_at']) ? date('d-m-y h:i A', strtotime($t['assigned_at'])) : '--'; ?></span>
                            </div>
                        <?php else: ?>
                            <span style="color:#ed1c24; font-size:11px;"><i class="fas fa-exclamation-circle"></i> এখনো কাউকে এসাইন করা হয়নি</span>
                        <?php endif; ?>

                        <?php if($t['status'] == 'Resolved' && !empty($t['resolved_at'])): ?>
                            <span style="font-size:10px; color:var(--secondary); display:block; margin-top:3px;">সমাধান: <?php echo date('d-m-y h:i A', strtotime($t['resolved_at'])); ?></span>
                        <?php endif; ?>
                    </td>
                    <td><span class="badge <?php 
                        if($t['status'] == 'Resolved') echo 'bg-resolved';
                        elseif($t['status'] == 'In Progress') echo 'bg-in-progress';
                        else echo 'bg-pending';
                    ?>"><?php echo htmlspecialchars($t['status'] ?? 'Pending'); ?></span></td>
                    <td>
                        <button onclick='openTicket(<?php echo json_encode($t); ?>)' class="btn btn-primary" style="font-size: 11px;">ম্যানেজ</button>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="5" style="text-align:center; padding: 30px; color: #999;">কোনো টিকিট পাওয়া যায়নি।</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- ৪. টিকিট এডিট মোডাল -->
<div id="ticketModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
    <div style="background:white; padding:30px; border-radius:10px; width:90%; max-width: 500px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);">
        <h4 id="m_title" style="margin-top:0; color:var(--primary); border-bottom: 2px solid #f1f1f1; padding-bottom: 10px;">টিকিট আপডেট</h4>
        <form action="admin.php?view=tickets" method="POST">
            <input type="hidden" name="ticket_id" id="m_id">
            
            <div style="margin-bottom:15px;">
                <label style="font-weight: 600; display: block; margin-bottom: 5px;">কাকে এসাইন করবেন (Staff):</label>
                <select name="assigned_staff" id="m_staff" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:5px;">
                    <option value="">-- কাউকে এসাইন করা হয়নি --</option>
                    <?php 
                    mysqli_data_seek($staff_db_res, 0); 
                    while($st = mysqli_fetch_assoc($staff_db_res)): ?>
                        <option value="<?php echo htmlspecialchars($st['staff_name']); ?>"><?php echo htmlspecialchars($st['staff_name']); ?></option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div style="margin-bottom:15px;">
                <label style="font-weight: 600; display: block; margin-bottom: 5px;">টিকিট স্ট্যাটাস:</label>
                <select name="status" id="m_status" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:5px;">
                    <option value="Pending">Pending</option>
                    <option value="In Progress">In Progress</option>
                    <option value="Resolved">Resolved</option>
                </select>
            </div>

            <div style="margin-bottom:15px;">
                <label style="font-weight: 600; display: block; margin-bottom: 5px;">অ্যাডমিন রিপ্লাই / নোট:</label>
                <textarea name="admin_reply" id="m_reply" style="height:100px; width:100%; padding:10px; border:1px solid #ddd; border-radius:5px; box-sizing:border-box;"></textarea>
            </div>

            <div style="text-align:right; border-top: 1px solid #eee; padding-top: 15px;">
                <button type="button" onclick="document.getElementById('ticketModal').style.display='none'" class="btn" style="background:#ddd;">বন্ধ করুন</button>
                <button type="submit" name="update_ticket" class="btn" style="background:var(--primary); color:white;">তথ্য আপডেট করুন</button>
            </div>
        </form>
    </div>
</div>

<script>
function openTicket(data) {
    document.getElementById('m_id').value = data.id;
    document.getElementById('m_status').value = data.status || 'Pending';
    document.getElementById('m_staff').value = data.assigned_staff || '';
    document.getElementById('m_reply').value = data.admin_reply || '';
    document.getElementById('m_title').innerHTML = "<i class='fas fa-edit'></i> টিকিট #" + data.id + " ট্র্যাকিং ও আপডেট";
    document.getElementById('ticketModal').style.display = 'flex';
}
</script>