{% extends "base.html" %}
{% block title %}Cash Book{% endblock %}

{% block content %}
<style>
  :root {
    --primary-color: #4f46e5;
    --success-color: #10b981;
    --danger-color: #ef4444;
    --warning-color: #f59e0b;
    --bg-light: #f8fafc;
    --border-color: #e2e8f0;
    --shadow-sm: 0 1px 3px rgba(0,0,0,0.12);
    --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
    --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
  }

  body {
    background: var(--bg-light);
  }

  /* Modern Card Styling */
  .modern-card {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-md);
    border: 1px solid var(--border-color);
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 2px solid var(--border-color);
  }

  .section-header h2 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
    color: #1e293b;
  }

  .section-icon {
    font-size: 1.75rem;
  }

  /* Beautiful Table Styling */
  .beautiful-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: var(--shadow-md);
  }

  .beautiful-table thead {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .beautiful-table thead th {
    padding: 1rem 1.25rem;
    text-align: left;
    font-weight: 600;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: white;
    border: none;
  }

  .beautiful-table tbody tr {
    border-bottom: 1px solid var(--border-color);
    transition: all 0.3s ease;
  }

  .beautiful-table tbody tr:hover {
    background: var(--bg-light);
    transform: scale(1.01);
    box-shadow: var(--shadow-sm);
  }

  .beautiful-table tbody tr:last-child {
    border-bottom: none;
  }

  .beautiful-table tbody td {
    padding: 1.25rem 1.25rem;
    color: #334155;
    font-size: 0.95rem;
    vertical-align: middle;
  }

  /* Table Responsive Wrapper */
  .table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  /* ID Badge */
  .id-badge {
    display: inline-block;
    padding: 0.35rem 0.75rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 6px;
    font-weight: 600;
    font-size: 0.85rem;
  }

  /* Type Badges */
  .type-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.4rem 0.9rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.85rem;
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .type-credit {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    color: #065f46;
    border: 1px solid #6ee7b7;
  }

  .type-debit {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    color: #991b1b;
    border: 1px solid #fca5a5;
  }

  /* Amount Styling */
  .amount-cell {
    font-weight: 700;
    font-size: 1rem;
    color: #0f172a;
  }

  .amount-credit {
    color: var(--success-color);
  }

  .amount-debit {
    color: var(--danger-color);
  }

  /* Balance Indicator */
  .balance-cell {
    font-weight: 700;
    font-size: 1.05rem;
    padding: 0.6rem 1rem !important;
    border-radius: 8px;
  }

  .balance-positive {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    color: #065f46;
  }

  .balance-negative {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    color: #991b1b;
  }

  /* Action Buttons */
  .action-buttons {
    display: flex;
    gap: 0.5rem;
  }

  .btn-action {
    padding: 0.5rem 0.75rem;
    border-radius: 8px;
    border: none;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.2s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }

  .btn-action:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-md);
  }

  .btn-edit {
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    color: white;
  }

  .btn-delete {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
  }

  /* Search Bar */
  .search-container {
    margin-bottom: 1.5rem;
  }

  .input-group .form-control {
    border-right: none;
  }

  .input-group .btn {
    border-left: none;
    background: white;
    border: 2px solid var(--border-color);
    border-left: none;
  }

  /* Mobile Card View */
  @media (max-width: 768px) {
    .mobile-card {
      background: white;
      border-radius: 12px;
      padding: 1.5rem;
      margin-bottom: 1.5rem;
      box-shadow: var(--shadow-md);
      border: 1px solid var(--border-color);
    }
    
    .mobile-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1rem;
      padding-bottom: 1rem;
      border-bottom: 2px solid var(--border-color);
    }

    .mobile-id {
      font-size: 1rem;
      font-weight: 700;
      color: #1e293b;
    }
    
    .mobile-balance {
      padding: 0.5rem 1rem;
      border-radius: 8px;
      font-weight: 700;
      font-size: 0.95rem;
    }
    
    .mobile-card-row {
      display: flex;
      justify-content: space-between;
      padding: 0.75rem 0;
      border-bottom: 1px solid #f1f5f9;
    }
    
    .mobile-card-label {
      font-weight: 600;
      color: #64748b;
      font-size: 0.9rem;
    }
    
    .mobile-card-value {
      color: #1e293b;
      text-align: right;
      font-size: 0.95rem;
      font-weight: 500;
    }
    
    .mobile-card-actions {
      margin-top: 1.25rem;
      display: flex;
      gap: 0.75rem;
      justify-content: flex-end;
    }

    .modern-card {
      padding: 1.5rem;
    }
    
    .desktop-table {
      display: none;
    }
    
    .mobile-view {
      display: block;
    }

    .section-header h2 {
      font-size: 1.25rem;
    }
  }
  
  @media (min-width: 769px) {
    .mobile-view {
      display: none;
    }
    
    .desktop-table {
      display: block;
    }
  }

  /* Form Styling */
  .form-control, .form-select {
    border: 2px solid var(--border-color);
    border-radius: 8px;
    padding: 0.65rem 1rem;
    transition: all 0.2s ease;
  }

  .form-control:focus, .form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    outline: none;
  }

  .form-label {
    font-weight: 600;
    color: #475569;
    margin-bottom: 0.5rem;
    font-size: 0.9rem;
  }

  /* Buttons */
  .btn {
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 600;
    transition: all 0.2s ease;
    border: none;
  }

  .btn:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-md);
  }

  .btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
  }

  .btn-secondary {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    color: white;
  }

  .btn-outline-primary {
    border: 2px solid var(--primary-color);
    color: var(--primary-color);
    background: white;
  }

  .btn-outline-primary:hover {
    background: var(--primary-color);
    color: white;
  }

  .btn-outline-secondary {
    border: 2px solid #6b7280;
    color: #6b7280;
    background: white;
  }

  .btn-outline-secondary:hover {
    background: #6b7280;
    color: white;
  }

  /* Pagination */
  .pagination {
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .page-item .page-link {
    border: 2px solid var(--border-color);
    border-radius: 8px;
    color: #475569;
    font-weight: 600;
    padding: 0.5rem 1rem;
    transition: all 0.2s ease;
  }

  .page-item.active .page-link {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
    color: white;
  }

  .page-item .page-link:hover {
    background: var(--bg-light);
    transform: translateY(-2px);
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 3rem 2rem;
    color: #64748b;
  }

  .empty-state-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
  }
</style>

<!-- ============================================================================ -->
<!-- ADD/EDIT TRANSACTION FORM (Admin Only) -->
<!-- ============================================================================ -->

{% if session.get('role') == 'admin' %}
<div class="modern-card">
  <div class="section-header">
    <span class="section-icon">{{ "✏️" if edit_row else "➕" }}</span>
    <h2>{{ "Edit Transaction" if edit_row else "Add New Transaction" }}</h2>
  </div>

  <form method="POST" class="row g-3">
    <input type="hidden" name="edit_id" value="{{ edit_row.id if edit_row else '' }}">

    <div class="col-md-3">
      <label for="date" class="form-label">📅 Date</label>
      <input type="date" name="date" id="date" class="form-control" value="{{ edit_row.date if edit_row else '' }}" required>
    </div>

    <div class="col-md-3">
      <label for="reason" class="form-label">📝 Reason</label>
      <input type="text" name="reason" id="reason" class="form-control" value="{{ edit_row.reason if edit_row else '' }}" required>
    </div>

    <div class="col-md-2">
      <label for="amount" class="form-label">💰 Amount</label>
      <input type="number" step="0.01" name="amount" id="amount" class="form-control" value="{{ edit_row.amount if edit_row else '' }}" required>
    </div>

    <div class="col-md-2">
      <label for="type" class="form-label">🔄 Type</label>
      <select name="type" id="type" class="form-select" required>
        {% for t in types %}
        <option value="{{ t }}" {% if edit_row and edit_row.type == t %}selected{% endif %}>{{ t.capitalize() }}</option>
        {% endfor %}
      </select>
    </div>

    <div class="col-md-3">
      <label for="payment_method" class="form-label">💳 Payment Method</label>
      <select name="payment_method" id="payment_method" class="form-select" required>
        {% for pm in payment_methods %}
        <option value="{{ pm }}" {% if edit_row and edit_row.payment_method == pm %}selected{% endif %}>{{ pm }}</option>
        {% endfor %}
      </select>
    </div>

    <div class="col-md-3">
      <label for="payment_done_by" class="form-label">👤 Payment Done By</label>
      <select name="payment_done_by" id="payment_done_by" class="form-select" required>
        {% for pdb in payment_done_bys %}
        <option value="{{ pdb }}" {% if edit_row and edit_row.payment_done_by == pdb %}selected{% endif %}>{{ pdb }}</option>
        {% endfor %}
      </select>
    </div>

    <div class="col-md-6">
      <label for="description" class="form-label">📄 Description (Optional)</label>
      <input type="text" name="description" id="description" class="form-control" value="{{ edit_row.description if edit_row else '' }}" placeholder="Additional notes...">
    </div>

    <div class="col-12">
      <button type="submit" class="btn btn-primary">
        {{ "💾 Update Transaction" if edit_row else "💾 Add Transaction" }}
      </button>
      {% if edit_row %}
      <a href="{{ url_for('manage_cashbook') }}" class="btn btn-secondary ms-2">❌ Cancel</a>
      {% endif %}
    </div>
  </form>
</div>
{% endif %}

<!-- ============================================================================ -->
<!-- SEARCH & FILTER SECTION -->
<!-- ============================================================================ -->

<div class="modern-card">
  <div class="section-header">
    <span class="section-icon">🔍</span>
    <h2>Search & Filter Transactions</h2>
  </div>

  <!-- Search Bar -->
  <form method="GET" class="search-container">
    <div class="input-group">
      <input type="text" class="form-control" name="q" placeholder="🔎 Search by reason or description..."
             value="{{ search_query or '' }}">
      <button class="btn btn-outline-secondary" type="submit">🔍 Search</button>
    </div>
  </form>
  
  <!-- Filters -->
  <form method="GET" class="row g-3">
    <input type="hidden" name="q" value="{{ search_query or '' }}">
    
    <div class="col-md-3">
      <label for="start_date" class="form-label">📅 From Date</label>
      <input type="date" name="start_date" id="start_date" class="form-control" value="{{ filter_start_date }}">
    </div>
    
    <div class="col-md-3">
      <label for="end_date" class="form-label">📅 To Date</label>
      <input type="date" name="end_date" id="end_date" class="form-control" value="{{ filter_end_date }}">
    </div>
    
    <div class="col-md-3">
      <label for="payment_method_filter" class="form-label">💳 Payment Method</label>
      <select name="payment_method" id="payment_method_filter" class="form-select">
        <option value="All" {% if filter_payment_method == 'All' %}selected{% endif %}>All Methods</option>
        {% for pm in payment_methods %}
        <option value="{{ pm }}" {% if filter_payment_method == pm %}selected{% endif %}>{{ pm }}</option>
        {% endfor %}
      </select>
    </div>
    
    <div class="col-md-3">
      <label for="payment_done_by_filter" class="form-label">👤 Payment Done By</label>
      <select name="payment_done_by" id="payment_done_by_filter" class="form-select">
        <option value="All" {% if filter_payment_done_by == 'All' %}selected{% endif %}>All Users</option>
        {% for pdb in payment_done_bys %}
        <option value="{{ pdb }}" {% if filter_payment_done_by == pdb %}selected{% endif %}>{{ pdb }}</option>
        {% endfor %}
      </select>
    </div>
    
    <div class="col-12">
      <button type="submit" class="btn btn-outline-primary">✅ Apply Filters</button>
      <a href="{{ url_for('manage_cashbook') }}" class="btn btn-outline-secondary ms-2">🔄 Clear All</a>
    </div>
  </form>
</div>

<!-- ============================================================================ -->
<!-- TRANSACTIONS LIST -->
<!-- ============================================================================ -->

<div class="modern-card">
  <div class="section-header">
    <span class="section-icon">💰</span>
    <h2>Cash Book Transactions</h2>
  </div>

  <!-- Desktop Table View -->
  <div class="desktop-table">
    <div class="table-responsive">
      <table class="beautiful-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Date</th>
            <th>Reason</th>
            <th>Amount</th>
            <th>Type</th>
            <th>Payment Method</th>
            <th>Done By</th>
            <th>Description</th>
            <th>Balance</th>
            {% if session.get('role') == 'admin' %}
            <th>Actions</th>
            {% endif %}
          </tr>
        </thead>
        <tbody>
          {% for t in transactions %}
          <tr>
            <td><span class="id-badge">#{{ t.id }}</span></td>
            <td>{{ t.date }}</td>
            <td><strong>{{ t.reason }}</strong></td>
            <td class="amount-cell {{ 'amount-credit' if t.type == 'credit' else 'amount-debit' }}">
              {{ "+" if t.type == 'credit' else "-" }} Rs. {{ "{:,.2f}".format(t.amount) }}
            </td>
            <td>
              <span class="type-badge {{ 'type-credit' if t.type == 'credit' else 'type-debit' }}">
                {{ "📈" if t.type == 'credit' else "📉" }} {{ t.type.capitalize() }}
              </span>
            </td>
            <td>{{ t.payment_method }}</td>
            <td>{{ t.payment_done_by }}</td>
            <td>{{ t.description or "—" }}</td>
            <td>
              <span class="balance-cell {{ 'balance-positive' if t.running_balance >= 0 else 'balance-negative' }}">
                Rs. {{ "{:,.2f}".format(t.running_balance) }}
              </span>
            </td>
            {% if session.get('role') == 'admin' %}
            <td>
              <div class="action-buttons">
                <a href="?edit={{ t.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}" class="btn-action btn-edit" title="Edit">✏️</a>
                <a href="?delete={{ t.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}" 
                   onclick="return confirmDelete()" 
                   class="btn-action btn-delete" title="Delete">🗑️</a>
              </div>
            </td>
            {% endif %}
          </tr>
          {% else %}
          <tr>
            <td colspan="10" class="empty-state">
              <div class="empty-state-icon">📭</div>
              <p>No transactions found</p>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>

  <!-- Mobile Card View -->
  <div class="mobile-view">
    {% for t in transactions %}
    <div class="mobile-card">
      <div class="mobile-card-header">
        <span class="mobile-id">Transaction #{{ t.id }}</span>
        <span class="mobile-balance {{ 'balance-positive' if t.running_balance >= 0 else 'balance-negative' }}">
          Rs. {{ "{:,.2f}".format(t.running_balance) }}
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📅 Date:</span>
        <span class="mobile-card-value">{{ t.date }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📝 Reason:</span>
        <span class="mobile-card-value"><strong>{{ t.reason }}</strong></span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">💰 Amount:</span>
        <span class="mobile-card-value {{ 'amount-credit' if t.type == 'credit' else 'amount-debit' }}">
          {{ "+" if t.type == 'credit' else "-" }} Rs. {{ "{:,.2f}".format(t.amount) }}
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🔄 Type:</span>
        <span class="mobile-card-value">
          <span class="type-badge {{ 'type-credit' if t.type == 'credit' else 'type-debit' }}">
            {{ "📈" if t.type == 'credit' else "📉" }} {{ t.type.capitalize() }}
          </span>
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">💳 Payment Method:</span>
        <span class="mobile-card-value">{{ t.payment_method }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">👤 Done By:</span>
        <span class="mobile-card-value">{{ t.payment_done_by }}</span>
      </div>
      
      {% if t.description %}
      <div class="mobile-card-row">
        <span class="mobile-card-label">📄 Description:</span>
        <span class="mobile-card-value">{{ t.description }}</span>
      </div>
      {% endif %}
      
      {% if session.get('role') == 'admin' %}
      <div class="mobile-card-actions">
        <a href="?edit={{ t.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}" class="btn-action btn-edit">✏️ Edit</a>
        <a href="?delete={{ t.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}" 
           onclick="return confirmDelete()" 
           class="btn-action btn-delete">🗑️ Delete</a>
      </div>
      {% endif %}
    </div>
    {% else %}
    <div class="empty-state">
      <div class="empty-state-icon">📭</div>
      <p>No transactions found</p>
    </div>
    {% endfor %}
  </div>
</div>

<!-- ============================================================================ -->
<!-- PAGINATION -->
<!-- ============================================================================ -->

<nav>
  <ul class="pagination justify-content-center mt-4">
    {% if current_page > 1 %}
    <li class="page-item">
      <a class="page-link" href="?page={{ current_page - 1 }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}">« Prev</a>
    </li>
    {% endif %}
    
    {% for page_num in range(1, total_pages + 1) %}
    <li class="page-item {% if page_num == current_page %}active{% endif %}">
      <a class="page-link" href="?page={{ page_num }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}">{{ page_num }}</a>
    </li>
    {% endfor %}
    
    {% if current_page < total_pages %}
    <li class="page-item">
      <a class="page-link" href="?page={{ current_page + 1 }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_payment_method != 'All' %}&payment_method={{ filter_payment_method }}{% endif %}{% if filter_payment_done_by != 'All' %}&payment_done_by={{ filter_payment_done_by }}{% endif %}">Next »</a>
    </li>
    {% endif %}
  </ul>
</nav>

<!-- ============================================================================ -->
<!-- JAVASCRIPT -->
<!-- ============================================================================ -->

<script>
  function confirmDelete() {
    if (!confirm("⚠️ Are you sure you want to delete this transaction?")) return false;
    const password = prompt("🔐 Enter password to confirm deletion:");
    if (password === "12345") return true;
    alert("❌ Incorrect password. Deletion canceled.");
    return false;
  }
</script>

{% endblock %}