<?php
include('session.php');
include_once('complaint_hierarchy.php');

$deleteMessage = '';
$deleteError = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_complaint'])) {
    $complaintId = (int)($_POST['complaint_id'] ?? 0);

    if($complaintId <= 0) {
        $deleteError = 'Invalid complaint selected.';
    } else {
        $usageQuery = $conn->query("SELECT COUNT(*) AS total FROM users_complaint WHERE c_list='".$complaintId."'");
        $usage = $usageQuery ? (int)$usageQuery->fetch_assoc()['total'] : 0;

        if($usage > 0) {
            $deleteError = 'This complaint cannot be deleted because it is used in '.$usage.' registered complaint(s).';
        } else {
            $delete = $conn->query("DELETE FROM complaint_list WHERE cid='".$complaintId."' LIMIT 1");
            if($delete && $conn->affected_rows > 0) {
                $deleteMessage = 'Complaint deleted successfully.';
            } elseif($delete) {
                $deleteError = 'Complaint was not found or was already deleted.';
            } else {
                $deleteError = 'Unable to delete complaint: '.$conn->error;
            }
        }
    }
}

if(isset($_GET['export']) && $_GET['export'] === 'excel') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="complaint-list-'.date('Y-m-d').'.csv"');
    echo "\xEF\xBB\xBF";

    $output = fopen('php://output', 'w');
    fputcsv($output, ['Sr No.', 'Type', 'Category / Priority', 'Location', 'Item', 'Complaint Name', 'Priority', 'Subdivision', 'Code']);

    $exportComplaints = $conn->query("
        SELECT cl.*, s.value AS subdivision_name
        FROM complaint_list cl
        LEFT JOIN subdivision s ON s.id = cl.subdivision
        ORDER BY cl.complaint_type ASC, cl.node_id ASC, cl.code ASC, cl.details ASC
    ");
    $serial = 0;
    while($row = $exportComplaints->fetch_assoc()) {
        $parts = complaint_node_parts_for_list($conn, $row['node_id']);
        fputcsv($output, [
            ++$serial,
            $parts['type'] ?: 'N/A',
            $parts['category'] ?: 'N/A',
            $parts['location'] ?: '',
            $parts['item'] ?: '',
            $row['details'],
            $row['priority'],
            $row['subdivision_name'] ?: 'N/A',
            $row['code']
        ]);
    }
    fclose($output);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
	<title>ECIMS ADMIN | COMPLAINT LIST</title>
    <?php include('includes/head.php'); ?>
    <style>
        th,td {
            text-align:center;
        }
        .chain-cell {
            text-align: left;
            min-width: 150px;
        }
        .complaint-name {
            text-align: left;
            min-width: 260px;
            font-weight: 600;
        }
        .muted-dash {
            color: #999;
        }
        .report-actions {
            display: flex;
            gap: 8px;
        }
        @media print {
            @page {
                size: landscape;
                margin: 7mm;
            }
            .horizontal-menu, .no-print, footer {
                display: none !important;
            }
            .content-wrapper, .card, .card-body {
                margin: 0 !important;
                padding: 0 !important;
                background: #fff !important;
                box-shadow: none !important;
                border: 0 !important;
            }
            .table-responsive {
                overflow: visible !important;
            }
            .report-table {
                width: 100% !important;
                table-layout: fixed;
                font-size: 7px;
            }
            .report-table th, .report-table td {
                min-width: 0 !important;
                padding: 3px !important;
                white-space: normal !important;
                overflow-wrap: anywhere;
            }
        }
    </style>
  </head>
  <body>
    <div class="container-scroller">
      <div class="horizontal-menu">
        <?php include('includes/header.php'); ?>
      </div>
      <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
          <div class="content-wrapper">
            <div class="page-header">
              <h3 class="page-title"> All Complaints List </h3>
              <div class="report-actions no-print">
                <button type="button" class="btn btn-sm btn-primary" onclick="window.print()">Print</button>
                <a href="comp.php?export=excel" class="btn btn-sm btn-success">Export Excel</a>
              </div>
            </div>
            <?php if($deleteMessage !== '') { ?>
              <div class="alert alert-success"><?php echo complaint_html($deleteMessage); ?></div>
            <?php } ?>
            <?php if($deleteError !== '') { ?>
              <div class="alert alert-danger"><?php echo complaint_html($deleteError); ?></div>
            <?php } ?>
            <div class="card grid-margin">
              <div class="card-body">
                <div class="row">
                  <div class="col-12">
                    <div class="table-responsive">
                      <table id="dataTable" class="table table-striped table-bordered report-table" width="100%">
                        <thead>
                          <tr>
                            <th>Sr No.</th>
                            <th>Type</th>
                            <th>Category / Priority</th>
                            <th>Location</th>
                            <th>Item</th>
                            <th>Complaint Name</th>
                            <th>Priority</th>
                            <th>Subdivision</th>
                            <th>Code</th>
                            <th class="no-print">Actions</th>
                          </tr>
                        </thead>
                        <tbody>
                            <?php $count=0; $users_complaint = $conn->query("SELECT * FROM complaint_list ORDER BY complaint_type ASC, node_id ASC, code ASC, details ASC"); 
                            if($users_complaint->num_rows > 0) {
                            while($fetchusers_complaint = $users_complaint->fetch_assoc()) { $count++;
                            $subdivision = $conn->query("SELECT * FROM subdivision WHERE id='".(int)$fetchusers_complaint['subdivision']."'")->fetch_assoc();
                            $parts = complaint_node_parts_for_list($conn, $fetchusers_complaint['node_id']);
                            ?>
                              <tr>
                                <td><?php echo $count; ?></td>
                                <td class="chain-cell"><?php echo complaint_html($parts['type'] ?: 'N/A'); ?></td>
                                <td class="chain-cell"><?php echo complaint_html($parts['category'] ?: 'N/A'); ?></td>
                                <td class="chain-cell"><?php echo !empty($parts['location']) ? complaint_html($parts['location']) : '<span class="muted-dash">-</span>'; ?></td>
                                <td class="chain-cell"><?php echo !empty($parts['item']) ? complaint_html($parts['item']) : '<span class="muted-dash">-</span>'; ?></td>
                                <td class="complaint-name" title="<?php echo complaint_html(complaint_full_path($conn, $fetchusers_complaint)); ?>"><?php echo complaint_html($fetchusers_complaint['details']); ?></td>
                                <td><?php echo $fetchusers_complaint['priority']; ?></td>
                                <td><?php echo complaint_html($subdivision['value'] ?? 'N/A'); ?></td>
                                <td><?php echo $fetchusers_complaint['code']; ?></td>
                                <td class="no-print">
                                  <div class="d-flex justify-content-center">
                                    <a href="editComp.php?id=<?php echo (int)$fetchusers_complaint['cid']; ?>" class="btn btn-xs btn-outline-primary me-2">Update</a>
                                    <form method="POST" class="delete-complaint-form">
                                      <input type="hidden" name="complaint_id" value="<?php echo (int)$fetchusers_complaint['cid']; ?>">
                                      <button type="submit" name="delete_complaint" value="1" class="btn btn-xs btn-outline-danger">Delete</button>
                                    </form>
                                  </div>
                                </td>
                              </tr>
                          <?php }} else {
                          echo '<tr><td colspan="10"><center>No Records Found!</center></td></tr>';
                          } ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
		  <?php include('includes/footer.php'); ?>
        </div>
      </div>
    </div>
    </div>
    <?php include('includes/foot.php'); ?>
    <script>
      $(document).on('submit', '.delete-complaint-form', function() {
        return window.confirm('Are you sure you want to delete this complaint? This action cannot be undone.');
      });
    </script>
  </body>
</html>
