<?php
// Get single record for edit/view
$record = null;
if (($action === 'edit' || $action === 'view') && $id) {
    $record = fetchOne("SELECT * FROM credit_notes WHERE id = ?", [$id]);
}

// Generate note number for new record
$next_note_number = ($action === 'add') ? generateNoteNumber('credit') : '';
?>

<?php if ($action === 'list'): ?>
    <!-- List View -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
        <h1 class="h2"><i class="fas fa-credit-card me-2"></i>Credit Notes</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <a href="?page=credit&action=add" class="btn btn-primary">
                <i class="fas fa-plus me-1"></i>Add New Credit Note
            </a>
        </div>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <?php
            switch($_GET['success']) {
                case 'added': echo 'Credit note added successfully!'; break;
                case 'updated': echo 'Credit note updated successfully!'; break;
                case 'deleted': echo 'Credit note deleted successfully!'; break;
            }
            ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body">
            <?php
            $search = $_GET['search'] ?? '';
            $where = '';
            $params = [];
            
            if ($search) {
                $where = "WHERE note_number LIKE ? OR party_name LIKE ? OR original_invoice_no LIKE ?";
                $params = ["%$search%", "%$search%", "%$search%"];
            }
            
            $notes = fetchAll("SELECT * FROM credit_notes $where ORDER BY created_at DESC", $params);
            ?>
            
            <!-- Search -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <form method="GET" class="d-flex">
                        <input type="hidden" name="page" value="credit">
                        <input type="hidden" name="action" value="list">
                        <input type="text" class="form-control" name="search" placeholder="Search by note number, party name, or invoice..." value="<?= htmlspecialchars($search) ?>">
                        <button class="btn btn-outline-secondary" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>
                <div class="col-md-6 text-end">
                    <span class="text-muted">Total: <?= count($notes) ?> credit notes</span>
                </div>
            </div>

            <?php if (empty($notes)): ?>
                <div class="text-center p-5">
                    <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                    <h5 class="text-muted">No credit notes found</h5>
                    <?php if ($search): ?>
                        <p class="text-muted">Try adjusting your search criteria</p>
                        <a href="?page=credit&action=list" class="btn btn-outline-secondary">Clear Search</a>
                    <?php else: ?>
                        <a href="?page=credit&action=add" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i>Add Your First Credit Note
                        </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Note #</th>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Party Name</th>
                                <th>Original Invoice</th>
                                <th>Amount</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($notes as $note): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($note['note_number']) ?></strong></td>
                                <td><?= date('d/m/Y', strtotime($note['note_date'])) ?></td>
                                <td>
                                    <span class="badge bg-<?= $note['note_type'] === 'sales' ? 'primary' : 'warning' ?>">
                                        <?= ucfirst($note['note_type']) ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($note['party_name']) ?></td>
                                <td><?= htmlspecialchars($note['original_invoice_no']) ?></td>
                                <td>₹<?= number_format($note['total_amount'], 2) ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="?page=credit&action=view&id=<?= $note['id'] ?>" class="btn btn-outline-info" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="?page=credit&action=edit&id=<?= $note['id'] ?>" class="btn btn-outline-warning" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button onclick="confirmDelete('credit', <?= $note['id'] ?>, '<?= htmlspecialchars($note['note_number']) ?>')" class="btn btn-outline-danger" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

<?php elseif ($action === 'add' || $action === 'edit'): ?>
    <!-- Add/Edit Form -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
        <h1 class="h2">
            <i class="fas fa-<?= $action === 'add' ? 'plus' : 'edit' ?> me-2"></i>
            <?= ucfirst($action) ?> Credit Note
        </h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <a href="?page=credit&action=list" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>Back to List
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <form method="POST">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="note_number" class="form-label">Note Number *</label>
                            <input type="text" class="form-control" id="note_number" name="note_number" 
                                   value="<?= htmlspecialchars($record['note_number'] ?? $next_note_number) ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="note_date" class="form-label">Note Date *</label>
                            <input type="date" class="form-control" id="note_date" name="note_date" 
                                   value="<?= $record['note_date'] ?? date('Y-m-d') ?>" required>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="note_type" class="form-label">Note Type *</label>
                            <select class="form-select" id="note_type" name="note_type" required>
                                <option value="sales" <?= ($record['note_type'] ?? '') === 'sales' ? 'selected' : '' ?>>Sales</option>
                                <option value="purchase" <?= ($record['note_type'] ?? '') === 'purchase' ? 'selected' : '' ?>>Purchase</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="party_name" class="form-label">Party Name *</label>
                            <input type="text" class="form-control" id="party_name" name="party_name" 
                                   value="<?= htmlspecialchars($record['party_name'] ?? '') ?>" required>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="party_gstin" class="form-label">Party GSTIN</label>
                            <input type="text" class="form-control" id="party_gstin" name="party_gstin" 
                                   value="<?= htmlspecialchars($record['party_gstin'] ?? '') ?>" maxlength="15">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="party_address" class="form-label">Party Address</label>
                            <textarea class="form-control" id="party_address" name="party_address" rows="2"><?= htmlspecialchars($record['party_address'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="original_invoice_no" class="form-label">Original Invoice No *</label>
                            <input type="text" class="form-control" id="original_invoice_no" name="original_invoice_no" 
                                   value="<?= htmlspecialchars($record['original_invoice_no'] ?? '') ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="original_invoice_date" class="form-label">Original Invoice Date *</label>
                            <input type="date" class="form-control" id="original_invoice_date" name="original_invoice_date" 
                                   value="<?= $record['original_invoice_date'] ?? '' ?>" required>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label for="reason" class="form-label">Reason for Credit Note *</label>
                    <textarea class="form-control" id="reason" name="reason" rows="3" required><?= htmlspecialchars($record['reason'] ?? '') ?></textarea>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="taxable_amount" class="form-label">Taxable Amount *</label>
                            <input type="number" step="0.01" class="form-control" id="taxable_amount" name="taxable_amount" 
                                   value="<?= $record['taxable_amount'] ?? '' ?>" onchange="calculateGST()" required>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="cgst_rate" class="form-label">CGST Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="cgst_rate" name="cgst_rate" 
                                   value="<?= $record['cgst_rate'] ?? '0' ?>" onchange="calculateGST()">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="sgst_rate" class="form-label">SGST Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="sgst_rate" name="sgst_rate" 
                                   value="<?= $record['sgst_rate'] ?? '0' ?>" onchange="calculateGST()">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="igst_rate" class="form-label">IGST Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="igst_rate" name="igst_rate" 
                                   value="<?= $record['igst_rate'] ?? '0' ?>" onchange="calculateGST()">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="cgst_amount" class="form-label">CGST Amount</label>
                            <input type="number" step="0.01" class="form-control" id="cgst_amount" name="cgst_amount" 
                                   value="<?= $record['cgst_amount'] ?? '0' ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="sgst_amount" class="form-label">SGST Amount</label>
                            <input type="number" step="0.01" class="form-control" id="sgst_amount" name="sgst_amount" 
                                   value="<?= $record['sgst_amount'] ?? '0' ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="igst_amount" class="form-label">IGST Amount</label>
                            <input type="number" step="0.01" class="form-control" id="igst_amount" name="igst_amount" 
                                   value="<?= $record['igst_amount'] ?? '0' ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="mb-3">
                            <label for="total_amount" class="form-label">Total Amount</label>
                            <input type="number" step="0.01" class="form-control" id="total_amount" name="total_amount" 
                                   value="<?= $record['total_amount'] ?? '0' ?>" readonly>
                        </div>
                    </div>
                </div>

                <div class="text-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i><?= ucfirst($action) ?> Credit Note
                    </button>
                </div>
            </form>
        </div>
    </div>

<?php elseif ($action === 'view' && $record): ?>
    <!-- View Details -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
        <h1 class="h2"><i class="fas fa-eye me-2"></i>Credit Note Details</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <div class="btn-group me-2">
                <a href="?page=credit&action=edit&id=<?= $record['id'] ?>" class="btn btn-warning">
                    <i class="fas fa-edit me-1"></i>Edit
                </a>
            </div>
            <a href="?page=credit&action=list" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>Back to List
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr><th width="40%">Note Number:</th><td><?= htmlspecialchars($record['note_number']) ?></td></tr>
                        <tr><th>Note Date:</th><td><?= date('d/m/Y', strtotime($record['note_date'])) ?></td></tr>
                        <tr><th>Note Type:</th><td><span class="badge bg-<?= $record['note_type'] === 'sales' ? 'primary' : 'warning' ?>"><?= ucfirst($record['note_type']) ?></span></td></tr>
                        <tr><th>Party Name:</th><td><?= htmlspecialchars($record['party_name']) ?></td></tr>
                        <tr><th>Party GSTIN:</th><td><?= htmlspecialchars($record['party_gstin'] ?: 'N/A') ?></td></tr>
                        <tr><th>Party Address:</th><td><?= nl2br(htmlspecialchars($record['party_address'] ?: 'N/A')) ?></td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr><th width="40%">Original Invoice:</th><td><?= htmlspecialchars($record['original_invoice_no']) ?></td></tr>
                        <tr><th>Invoice Date:</th><td><?= date('d/m/Y', strtotime($record['original_invoice_date'])) ?></td></tr>
                        <tr><th>Reason:</th><td><?= nl2br(htmlspecialchars($record['reason'])) ?></td></tr>
                        <tr><th>Created:</th><td><?= date('d/m/Y H:i', strtotime($record['created_at'])) ?></td></tr>
                        <tr><th>Updated:</th><td><?= date('d/m/Y H:i', strtotime($record['updated_at'])) ?></td></tr>
                    </table>
                </div>
            </div>
            
            <hr>
            
            <h5>GST Breakdown</h5>
            <div class="row">
                <div class="col-md-8">
                    <table class="table table-bordered">
                        <tr>
                            <th>Description</th>
                            <th>Rate (%)</th>
                            <th>Amount (₹)</th>
                        </tr>
                        <tr>
                            <td>Taxable Amount</td>
                            <td>-</td>
                            <td><?= number_format($record['taxable_amount'], 2) ?></td>
                        </tr>
                        <?php if ($record['cgst_amount'] > 0): ?>
                        <tr>
                            <td>CGST</td>
                            <td><?= $record['cgst_rate'] ?></td>
                            <td><?= number_format($record['cgst_amount'], 2) ?></td>
                        </tr>
                        <?php endif; ?>
                        <?php if ($record['sgst_amount'] > 0): ?>
                        <tr>
                            <td>SGST</td>
                            <td><?= $record['sgst_rate'] ?></td>
                            <td><?= number_format($record['sgst_amount'], 2) ?></td>
                        </tr>
                        <?php endif; ?>
                        <?php if ($record['igst_amount'] > 0): ?>
                        <tr>
                            <td>IGST</td>
                            <td><?= $record['igst_rate'] ?></td>
                            <td><?= number_format($record['igst_amount'], 2) ?></td>
                        </tr>
                        <?php endif; ?>
                        <tr class="table-primary">
                            <td><strong>Total Amount</strong></td>
                            <td>-</td>
                            <td><strong><?= number_format($record['total_amount'], 2) ?></strong></td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>

<?php else: ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-triangle me-2"></i>Record not found.
    </div>
<?php endif; ?>
