<?php
require_once 'config.php';

$page = $_GET['page'] ?? 'dashboard';
$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;

// Handle form submissions and redirects BEFORE any HTML output
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($page === 'credit' || $page === 'debit')) {
    $note_data = [
        'note_number' => $_POST['note_number'],
        'note_date' => $_POST['note_date'],
        'note_type' => $_POST['note_type'],
        'party_name' => $_POST['party_name'],
        'party_gstin' => $_POST['party_gstin'],
        'party_address' => $_POST['party_address'],
        'original_invoice_no' => $_POST['original_invoice_no'],
        'original_invoice_date' => $_POST['original_invoice_date'],
        'reason' => $_POST['reason'],
        'taxable_amount' => $_POST['taxable_amount'],
        'cgst_rate' => $_POST['cgst_rate'],
        'sgst_rate' => $_POST['sgst_rate'],
        'igst_rate' => $_POST['igst_rate']
    ];
    
    // Calculate GST amounts
    $gst_calc = calculateGST($note_data['taxable_amount'], $note_data['cgst_rate'], $note_data['sgst_rate'], $note_data['igst_rate']);
    $note_data = array_merge($note_data, $gst_calc);
    
    $table_name = $page . '_notes';
    
    if ($action === 'add') {
        $query = "INSERT INTO $table_name (note_number, note_date, note_type, party_name, party_gstin, party_address, 
                  original_invoice_no, original_invoice_date, reason, taxable_amount, cgst_rate, cgst_amount, 
                  sgst_rate, sgst_amount, igst_rate, igst_amount, total_amount) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        executeQuery($query, [
            $note_data['note_number'], $note_data['note_date'], $note_data['note_type'], 
            $note_data['party_name'], $note_data['party_gstin'], $note_data['party_address'],
            $note_data['original_invoice_no'], $note_data['original_invoice_date'], $note_data['reason'],
            $note_data['taxable_amount'], $note_data['cgst_rate'], $note_data['cgst_amount'],
            $note_data['sgst_rate'], $note_data['sgst_amount'], $note_data['igst_rate'], 
            $note_data['igst_amount'], $note_data['total_amount']
        ]);
        
        header("Location: ?page=$page&action=list&success=added");
        exit;
    } elseif ($action === 'edit' && $id) {
        $query = "UPDATE $table_name SET note_number=?, note_date=?, note_type=?, party_name=?, party_gstin=?, 
                  party_address=?, original_invoice_no=?, original_invoice_date=?, reason=?, taxable_amount=?, 
                  cgst_rate=?, cgst_amount=?, sgst_rate=?, sgst_amount=?, igst_rate=?, igst_amount=?, total_amount=? 
                  WHERE id=?";
        
        executeQuery($query, [
            $note_data['note_number'], $note_data['note_date'], $note_data['note_type'], 
            $note_data['party_name'], $note_data['party_gstin'], $note_data['party_address'],
            $note_data['original_invoice_no'], $note_data['original_invoice_date'], $note_data['reason'],
            $note_data['taxable_amount'], $note_data['cgst_rate'], $note_data['cgst_amount'],
            $note_data['sgst_rate'], $note_data['sgst_amount'], $note_data['igst_rate'], 
            $note_data['igst_amount'], $note_data['total_amount'], $id
        ]);
        
        header("Location: ?page=$page&action=list&success=updated");
        exit;
    }
}

// Handle delete actions BEFORE any HTML output
if ($action === 'delete' && $id && ($page === 'credit' || $page === 'debit')) {
    $table_name = $page . '_notes';
    executeQuery("DELETE FROM $table_name WHERE id = ?", [$id]);
    header("Location: ?page=$page&action=list&success=deleted");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GST Credit & Debit Notes</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            width: 220px;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 0.4rem 0.8rem;
            border-radius: 0.25rem;
            margin: 0.1rem 0;
            font-size: 0.875rem;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .sidebar h4 { font-size: 1.1rem; margin-bottom: 0.5rem; }
        .sidebar h6 { font-size: 0.75rem; margin-bottom: 0.3rem; margin-top: 0.8rem; }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
            padding: 0.5rem 1rem;
        }
        .card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
            border-radius: 0.375rem;
            margin-bottom: 0.75rem;
        }
        .card-body {
            padding: 0.75rem;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 0.375rem 0.375rem 0 0 !important;
            padding: 0.5rem 0.75rem;
            font-size: 1rem;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 0.375rem 0.75rem;
            font-size: 0.875rem;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
        .table {
            font-size: 0.875rem;
            margin-bottom: 0;
        }
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            padding: 0.5rem 0.75rem;
            font-size: 0.8rem;
        }
        .table td {
            padding: 0.5rem 0.75rem;
            vertical-align: middle;
        }
        .stats-card {
            border-left: 3px solid;
        }
        .stats-card.credit { border-left-color: #28a745; }
        .stats-card.debit { border-left-color: #dc3545; }
        .stats-card.sales { border-left-color: #007bff; }
        .stats-card.purchase { border-left-color: #ffc107; }
        .stats-card .card-body {
            padding: 0.6rem 0.8rem;
        }
        .stats-card h3 { font-size: 1.4rem; margin-bottom: 0.2rem; }
        .stats-card h6 { font-size: 0.75rem; margin-bottom: 0.3rem; }
        .form-control, .form-select {
            font-size: 0.875rem;
            padding: 0.375rem 0.5rem;
        }
        .form-label {
            font-size: 0.8rem;
            margin-bottom: 0.3rem;
            font-weight: 600;
        }
        .mb-3 {
            margin-bottom: 0.75rem !important;
        }
        .pb-2 {
            padding-bottom: 0.3rem !important;
        }
        .mb-3 {
            margin-bottom: 0.75rem !important;
        }
        .pt-3 {
            padding-top: 0.75rem !important;
        }
        h1.h2 {
            font-size: 1.3rem;
        }
        .border-bottom {
            border-bottom: 1px solid #e9ecef !important;
            margin-bottom: 0.75rem !important;
        }
        .alert {
            padding: 0.5rem 0.75rem;
            margin-bottom: 0.75rem;
            font-size: 0.875rem;
        }
        .badge {
            font-size: 0.7rem;
        }
        .btn-toolbar .btn-group {
            margin-right: 0.3rem;
        }
        .row { margin-bottom: 0; }
        .text-center.p-5 { padding: 2rem !important; }
        .text-center.p-4 { padding: 1.5rem !important; }
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                min-height: auto;
            }
            .main-content {
                padding: 0.25rem 0.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse position-fixed">
                <div class="position-sticky pt-2">
                    <div class="text-center mb-2">
                        <h4 class="text-white"><i class="fas fa-file-invoice me-1"></i>GST Notes</h4>
                        <hr class="text-white my-2">
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link <?= $page === 'dashboard' ? 'active' : '' ?>" href="?page=dashboard">
                                <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                            </a>
                        </li>
                        
                        <li class="nav-item">
                            <h6 class="text-white-50 text-uppercase small fw-bold">Credit Notes</h6>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $page === 'credit' && $action === 'list' ? 'active' : '' ?>" href="?page=credit&action=list">
                                <i class="fas fa-list me-1"></i>View All
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $page === 'credit' && $action === 'add' ? 'active' : '' ?>" href="?page=credit&action=add">
                                <i class="fas fa-plus me-1"></i>Add New
                            </a>
                        </li>
                        
                        <li class="nav-item">
                            <h6 class="text-white-50 text-uppercase small fw-bold">Debit Notes</h6>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $page === 'debit' && $action === 'list' ? 'active' : '' ?>" href="?page=debit&action=list">
                                <i class="fas fa-list me-1"></i>View All
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $page === 'debit' && $action === 'add' ? 'active' : '' ?>" href="?page=debit&action=add">
                                <i class="fas fa-plus me-1"></i>Add New
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 offset-md-3 offset-lg-2 main-content">
                <div class="pt-2 pb-1 mb-2">
                    <?php
                    switch($page) {
                        case 'dashboard':
                            include 'pages/dashboard.php';
                            break;
                        case 'credit':
                            include 'pages/credit_notes.php';
                            break;
                        case 'debit':
                            include 'pages/debit_notes.php';
                            break;
                        default:
                            include 'pages/dashboard.php';
                    }
                    ?>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-calculate GST amounts
        function calculateGST() {
            const taxableAmount = parseFloat(document.getElementById('taxable_amount').value) || 0;
            const cgstRate = parseFloat(document.getElementById('cgst_rate').value) || 0;
            const sgstRate = parseFloat(document.getElementById('sgst_rate').value) || 0;
            const igstRate = parseFloat(document.getElementById('igst_rate').value) || 0;
            
            const cgstAmount = (taxableAmount * cgstRate) / 100;
            const sgstAmount = (taxableAmount * sgstRate) / 100;
            const igstAmount = (taxableAmount * igstRate) / 100;
            const totalAmount = taxableAmount + cgstAmount + sgstAmount + igstAmount;
            
            if(document.getElementById('cgst_amount')) document.getElementById('cgst_amount').value = cgstAmount.toFixed(2);
            if(document.getElementById('sgst_amount')) document.getElementById('sgst_amount').value = sgstAmount.toFixed(2);
            if(document.getElementById('igst_amount')) document.getElementById('igst_amount').value = igstAmount.toFixed(2);
            if(document.getElementById('total_amount')) document.getElementById('total_amount').value = totalAmount.toFixed(2);
        }
        
        // Confirm delete
        function confirmDelete(type, id, noteNumber) {
            if(confirm(`Are you sure you want to delete ${type} note ${noteNumber}?`)) {
                window.location.href = `?page=${type}&action=delete&id=${id}`;
            }
        }
    </script>
</body>
</html>
