<?php 
// Get user information for sidebar
$user = get_user_information($connect);
$user = $user[0];

require 'sidebar.view.php'; 
?>

<style>
.modern-header {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    padding: 32px;
    border-radius: 12px;
    color: white;
    margin-bottom: 24px;
    box-shadow: 0 4px 16px rgba(240, 147, 251, 0.3);
}

.modern-header h1 {
    font-size: 28px;
    font-weight: 700;
    margin: 0 0 8px 0;
}

.modern-header p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-bottom: 24px;
}

.filter-card h6 {
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 16px;
    font-size: 16px;
}

.filter-group {
    margin-bottom: 16px;
}

.filter-group label {
    font-size: 13px;
    font-weight: 600;
    color: #6b7280;
    margin-bottom: 6px;
    display: block;
}

.filter-btn {
    width: 100%;
    padding: 10px;
    border-radius: 8px;
    border: 2px solid #e5e7eb;
    background: white;
    font-weight: 600;
    transition: all 0.2s;
    margin-bottom: 8px;
}

.filter-btn:hover {
    border-color: #f5576c;
    background: #fff5f7;
    color: #f5576c;
}

.filter-btn.active {
    border-color: #f5576c;
    background: #f5576c;
    color: white;
}

.action-bar {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-bottom: 24px;
}

.table-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.modern-table {
    border-radius: 8px;
    overflow: hidden;
}

.modern-table thead {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
}

.modern-table thead th {
    border: none;
    padding: 16px 12px;
    font-weight: 600;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.modern-table tbody td {
    padding: 16px 12px;
    vertical-align: middle;
    border-bottom: 1px solid #f3f4f6;
}

.modern-table tbody tr:hover {
    background: #fff5f7;
}

.coupon-img {
    width: 80px;
    height: 50px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.badge-modern {
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.btn-modern {
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.2s;
}

.btn-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.stats-mini {
    display: flex;
    gap: 16px;
    margin-top: 16px;
}

.stat-mini {
    flex: 1;
    background: rgba(255,255,255,0.2);
    padding: 12px;
    border-radius: 8px;
    text-align: center;
}

.stat-mini-value {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 4px;
}

.stat-mini-label {
    font-size: 12px;
    opacity: 0.9;
}

.coupon-code-badge {
    background: #1f2937;
    color: white;
    padding: 8px 12px;
    border-radius: 6px;
    font-family: 'Courier New', monospace;
    font-weight: 700;
    font-size: 12px;
    letter-spacing: 1px;
}
</style>

<section class="page-container">
  <div class="page-content-wrapper">
    <div class="content sm-gutter">
      <div class="container-fluid padding-25 sm-padding-10">
        
        <!-- Modern Header -->
        <div class="modern-header">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h1><i class="dripicons-broadcast"></i> Coupons Management</h1>
              <p>Manage all your coupons, deals, and promotional offers</p>
            </div>
            <div class="stats-mini">
              <div class="stat-mini">
                <div class="stat-mini-value" id="totalCoupons">-</div>
                <div class="stat-mini-label">Total</div>
              </div>
              <div class="stat-mini">
                <div class="stat-mini-value" id="activeCoupons">-</div>
                <div class="stat-mini-label">Active</div>
              </div>
              <div class="stat-mini">
                <div class="stat-mini-value" id="featuredCoupons">-</div>
                <div class="stat-mini-label">Featured</div>
              </div>
              <div class="stat-mini">
                <div class="stat-mini-value" id="verifiedCoupons">-</div>
                <div class="stat-mini-label">Verified</div>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <!-- Sidebar Filters -->
          <div class="col-lg-3 mb-4">
            <div class="filter-card">
              <h6><i class="fa fa-filter"></i> Filters</h6>
              
              <div class="filter-group">
                <label>Status</label>
                <button class="filter-btn active" data-filter="all" data-column="8">
                  <i class="fa fa-list"></i> All Coupons
                </button>
                <button class="filter-btn" data-filter="Enabled" data-column="8">
                  <i class="fa fa-check-circle"></i> Active Only
                </button>
                <button class="filter-btn" data-filter="Disabled" data-column="8">
                  <i class="fa fa-times-circle"></i> Inactive Only
                </button>
                <button class="filter-btn" data-filter="Pending" data-column="8">
                  <i class="fa fa-clock-o"></i> Pending Only
                </button>
              </div>

              <div class="filter-group">
                <label>Type</label>
                <button class="filter-btn" data-filter="Featured" data-column="6">
                  <i class="fa fa-star"></i> Featured Only
                </button>
                <button class="filter-btn" data-filter="Verified" data-column="7">
                  <i class="fa fa-check-circle"></i> Verified Only
                </button>
              </div>

              <div class="filter-group">
                <label>Search</label>
                <input type="text" id="searchCoupon" class="form-control" placeholder="Search coupons...">
              </div>

              <hr>

              <div class="filter-group">
                <button class="btn btn-primary btn-block" onclick="location.href='../controller/new_coupon.php'">
                  <i class="fa fa-plus"></i> Add New Coupon
                </button>
                <button class="btn btn-success btn-block" data-toggle="modal" data-target="#importExportModal">
                  <i class="ti ti-file-import"></i> Import / Export
                </button>
              </div>
            </div>

            <!-- Quick Stats -->
            <div class="filter-card">
              <h6><i class="fa fa-chart-bar"></i> Quick Stats</h6>
              <div style="font-size: 13px; color: #6b7280;">
                <div class="d-flex justify-content-between mb-2">
                  <span>With Codes:</span>
                  <strong id="couponsWithCode">-</strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                  <span>Deals (No Code):</span>
                  <strong id="couponsWithoutCode">-</strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                  <span>Pending Review:</span>
                  <strong id="pendingCoupons">-</strong>
                </div>
              </div>
            </div>
          </div>

          <!-- Main Content -->
          <div class="col-lg-9">
            <!-- Action Bar -->
            <div class="action-bar">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <span style="font-weight: 600; color: #1f2937;">
                    <span id="displayCount">0</span> coupons found
                  </span>
                </div>
                <div>
                  <select id="bulkAction" class="form-control form-control-sm" style="display: inline-block; width: auto; margin-right: 8px;">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Activate Selected</option>
                    <option value="deactivate">Deactivate Selected</option>
                    <option value="feature">Feature Selected</option>
                    <option value="unfeature">Unfeature Selected</option>
                    <option value="verify">Verify Selected</option>
                    <option value="unverify">Unverify Selected</option>
                    <option value="delete">Delete Selected</option>
                  </select>
                  <button class="btn btn-sm btn-primary" onclick="applyBulkAction()">
                    Apply
                  </button>
                </div>
              </div>
            </div>

            <!-- Table -->
            <div class="table-card">
              <div class="table-responsive">
                <table id="table_id" class="table modern-table" cellspacing="0" width="100%">
                  <thead>
                    <tr>
                      <th><input type="checkbox" id="selectAll"></th>
                      <th>ID</th>
                      <th>Image</th>
                      <th>Title</th>
                      <th>Store</th>
                      <th>Code</th>
                      <th>Featured</th>
                      <th>Verified</th>
                      <th>Status</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</section>

<!-- Import/Export Modal -->
<div class="modal fade" id="importExportModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
        <h5 class="modal-title"><i class="ti ti-file-import"></i> Import / Export Coupons</h5>
        <button type="button" class="close text-white" data-dismiss="modal">
          <span>&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-6">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title"><i class="ti ti-download"></i> Export Coupons</h5>
                <p class="card-text">Download all coupons as CSV file.</p>
                <a href="../controller/import_export.php?action=export_coupons" class="btn btn-primary">
                  <i class="ti ti-download"></i> Export Coupons CSV
                </a>
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title"><i class="ti ti-upload"></i> Import Coupons</h5>
                <p class="card-text">Upload CSV file to import coupons.</p>
                <form method="post" action="../controller/import_export.php?action=import_coupons" enctype="multipart/form-data">
                  <div class="form-group">
                    <input type="file" name="csv_file" class="form-control-file" accept=".csv" required>
                    <small class="form-text text-muted">
                      <strong>Format:</strong> Title, Merchant, Description, Coupon Code, URL, Start Date, End Date
                    </small>
                  </div>
                  <button type="submit" class="btn btn-primary">
                    <i class="ti ti-upload"></i> Import Coupons
                  </button>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div class="row mt-3">
          <div class="col-12">
            <div class="alert alert-info">
              <h6>Import Notes:</h6>
              <ul class="mb-0">
                <li>Stores will be automatically created if they don't exist</li>
                <li>Date format: DD-MM-YYYY (e.g., 20-05-2025)</li>
                <li>Categories and images will be set to default</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){
  var table = $('#table_id').DataTable({
   "bProcessing": true,
   "sAjaxSource": "../controller/get_coupons.php",
   "responsive": true,
   "bPaginate":true,
   "aaSorting": [[1,'desc']],
   "sPaginationType":"full_numbers",
   "iDisplayLength": 10,
   "aoColumns": [
   { "mData": null, "width": "3%", "className": "text-center", "orderable": false,
     "mRender": function(data) {
       return '<input type="checkbox" class="row-select" data-id="'+data.coupon_id+'">';
     }
   },
   { mData: 'coupon_id', "width": "4%", "className": "text-center" },
   { "mData": null , "width": "8%", "className": "text-center",
     "mRender" : function (data) {
      if(data.coupon_image){
        return "<img src='"+IMAGES_FOLDER+data.coupon_image+"' class='coupon-img'/>";
      }else{
        return "<img src='../assets/images/no-image.png' class='coupon-img'/>";
      }
    }
    },
    { mData: 'coupon_title', "width": "20%" },
    { "mData": null, "width": "10%",
     "mRender" : function (data) {
      if (data.store_title) {
        return '<span class="badge badge-primary badge-modern">' + data.store_title + '</span>';
      } else {
        return '<span class="text-muted" style="font-size: 11px;">No store</span>';
      }
     }
    },
    { "mData": null, "width": "10%", "className": "text-center",
     "mRender" : function (data) {
      if (data.coupon_code && data.coupon_code.trim() !== '') {
        return '<span class="coupon-code-badge">' + data.coupon_code + '</span>';
      } else {
        return '<span class="badge badge-secondary badge-modern">Deal</span>';
      }
     }
    },
    { "mData": null , "width": "8%", "className":"text-center",
     "mRender" : function (data) {
      if (data.coupon_featured == 1) {
        return '<span class="badge badge-warning badge-modern"><i class="fa fa-star"></i> Featured</span>';
      }else{
        return '<span class="badge badge-secondary badge-modern">Regular</span>';
        }
      }
    },
    { "mData": null , "width": "8%", "className":"text-center",
     "mRender" : function (data) {
      if (data.coupon_verify == 1) {
        return '<span class="badge badge-success badge-modern"><i class="fa fa-check-circle"></i> Verified</span>';
      }else{
        return '<span class="badge badge-secondary badge-modern">Unverified</span>';
        }
      }
    },
    { "mData": null , "width": "8%", "className":"text-center",
     "mRender" : function (data) {
      if (data.coupon_status == 1) {
        return '<span class="badge badge-success badge-modern"><i class="fa fa-check"></i> Enabled</span>';
      }else if (data.coupon_status == 2) {
        return '<span class="badge badge-danger badge-modern"><i class="fa fa-times"></i> Disabled</span>';
      }else if (data.coupon_status == 3) {
        return '<span class="badge badge-warning badge-modern"><i class="fa fa-clock-o"></i> Pending</span>';
      }
      }
    },
    { "mData": null ,
    "width": "12%",
    "className": "text-center",
    'orderable': false,
    'searchable': false,
    "mRender" : function (data) {
      return "<a class='btn btn-sm btn-primary btn-modern' href='../controller/edit_coupon.php?id="+data.coupon_id+"'><i class='fa fa-edit'></i> Edit</a> <a class='btn btn-sm btn-danger btn-modern deleteItem' data-url='../controller/delete_coupon.php?id="+data.coupon_id+"'><i class='fa fa-trash'></i></a>";}
    }
    ],
  "drawCallback": function() {
    updateStats();
  }
  });

// Search functionality
$('#searchCoupon').on('keyup', function() {
  table.search(this.value).draw();
});

// Filter buttons
$('.filter-btn').on('click', function() {
  var $this = $(this);
  var filter = $this.data('filter');
  var column = $this.data('column');
  
  // Remove active from buttons in same group
  $this.siblings('.filter-btn').removeClass('active');
  
  if ($this.hasClass('active')) {
    $this.removeClass('active');
    if (column) {
      table.columns(column).search('').draw();
    }
  } else {
    $this.addClass('active');
    if (filter === 'all') {
      table.columns(column).search('').draw();
    } else if (column) {
      table.columns(column).search(filter).draw();
    }
  }
});

// Select all checkbox
$('#selectAll').on('change', function() {
  $('.row-select').prop('checked', this.checked);
});

// Update stats
function updateStats() {
  $.get('../controller/get_coupons_stats.php', function(data) {
    $('#totalCoupons').text(data.total || 0);
    $('#activeCoupons').text(data.active || 0);
    $('#featuredCoupons').text(data.featured || 0);
    $('#verifiedCoupons').text(data.verified || 0);
    $('#couponsWithCode').text(data.with_code || 0);
    $('#couponsWithoutCode').text(data.without_code || 0);
    $('#pendingCoupons').text(data.pending || 0);
    $('#displayCount').text(table.page.info().recordsDisplay);
  }, 'json').fail(function() {
    // Fallback if stats endpoint doesn't exist
    $('#displayCount').text(table.page.info().recordsDisplay);
  });
}

updateStats();
});

function applyBulkAction() {
  var action = $('#bulkAction').val();
  if (!action) {
    alert('Please select an action');
    return;
  }
  
  var selected = [];
  $('.row-select:checked').each(function() {
    selected.push($(this).data('id'));
  });
  
  if (selected.length === 0) {
    alert('Please select at least one coupon');
    return;
  }
  
  if (confirm('Apply ' + action + ' to ' + selected.length + ' coupon(s)?')) {
    // Implement bulk action logic here
    console.log('Bulk action:', action, 'IDs:', selected);
  }
}
</script>
