# GST Credit & Debit Notes Module with Advanced Reporting

A comprehensive PHP module for managing GST Credit Notes and Debit Notes with advanced reporting capabilities and export options.

## 🚀 Features

### Core Functionality
- **Credit Notes Management**: Create, edit, and manage credit notes for sales and purchases
- **Debit Notes Management**: Create, edit, and manage debit notes for sales and purchases  
- **GST Calculations**: Automatic calculation of CGST, SGST, and IGST amounts
- **Party Management**: Support for both registered (with GSTIN) and unregistered parties
- **Dashboard**: Comprehensive overview with statistics and recent transactions

### 📊 Advanced Reporting System

#### 1. GST Reports (`pages/reports.php`)
Comprehensive reporting with multiple report types and export options:

**📋 Report Types:**
- **Summary Report**: Overview of all credit and debit notes with totals
- **Detailed Report**: Complete transaction-wise listing with all details
- **GST Summary Report**: Grouped by date, month, party, or GST rate
- **Party Wise Report**: Consolidated report by party with totals
- **Monthly Report**: Month-wise breakdown of transactions

**📤 Export Options:**
- **Excel Export** (.xls): Professional Excel format with formatting
- **PDF Export**: Print-ready PDF reports
- **CSV Export**: Data export for further analysis
- **Print View**: Browser-optimized print format

**✨ Key Features:**
- Dynamic filtering by date range, note type, and transaction type
- Interactive date range picker with preset periods (This Month, Last Month, This Quarter, etc.)
- Real-time report generation with AJAX
- Responsive design for mobile and desktop
- Advanced search and filtering options

#### 2. GST Returns (`pages/gst_returns.php`)
Specialized reports for GST return preparation:

**📋 GSTR-1 (Outward Supplies):**
- Credit notes and debit notes for sales transactions
- Separate sections for registered (CDNR) and unregistered (CDNUR) parties
- Net tax effect calculation
- JSON export for GST portal upload compatibility

**📋 GSTR-2 (Inward Supplies):**
- Credit notes and debit notes for purchase transactions
- Input Tax Credit (ITC) impact calculation
- Supplier-wise classification
- Compliance-ready format

**📋 GSTR-3B Summary:**
- Overall impact on tax liability
- Outward and inward supply adjustments
- Tax-wise breakdown (CGST, SGST, IGST)
- Net liability calculation with visual indicators

### 🔧 Technical Implementation

#### Database Schema
```sql
-- Credit Notes Table
CREATE TABLE credit_notes (
    id INT PRIMARY KEY AUTO_INCREMENT,
    note_number VARCHAR(50) UNIQUE,
    note_date DATE,
    note_type ENUM('sales','purchase'),
    party_name VARCHAR(255),
    party_gstin VARCHAR(15),
    party_address TEXT,
    original_invoice_no VARCHAR(50),
    original_invoice_date DATE,
    reason TEXT,
    taxable_amount DECIMAL(12,2),
    cgst_rate DECIMAL(5,2),
    cgst_amount DECIMAL(12,2),
    sgst_rate DECIMAL(5,2), 
    sgst_amount DECIMAL(12,2),
    igst_rate DECIMAL(5,2),
    igst_amount DECIMAL(12,2),
    total_amount DECIMAL(12,2),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Debit Notes Table (similar structure)
```

#### Key PHP Functions

**Report Generation:**
```php
- getReportData(): Main report data fetcher with filtering
- getSummaryReport(): Summary statistics and totals
- getDetailedReport(): Transaction-level details with search
- getGSTSummaryReport(): GST-focused summaries with grouping
- getPartyWiseReport(): Party-wise consolidation
```

**GST Returns:**
```php
- getGSTR1Data(): GSTR-1 compliance data for outward supplies
- getGSTR2Data(): GSTR-2 compliance data for inward supplies  
- getGSTR3BData(): GSTR-3B summary calculations
```

**Export Functions:**
```php
- exportToExcel(): Excel generation with formatting
- exportToPDF(): PDF creation with headers and styling
- exportToCSV(): CSV formatting for data analysis
- downloadJSON(): JSON export for GST portal integration
```

## 📖 Usage Instructions

### 1. Basic Operation
1. Navigate to GST Notes module via `index.php`
2. Create credit/debit notes using the sidebar navigation
3. Access reports via "Reports" menu
4. Select report type and configure filters
5. Generate and export reports as needed

### 2. Advanced Reporting
1. **Go to Reports section**
2. **Select Report Type:**
   - Summary: Quick overview with totals
   - Detailed: Full transaction listing
   - GST Summary: Tax-focused analysis
   - Party Wise: Customer/Supplier consolidation
   - Monthly: Time-series analysis

3. **Configure Filters:**
   - Date Range: Use date picker or select presets
   - Note Type: Credit, Debit, or Both
   - Transaction Type: Sales, Purchase, or Both
   - Party Name: Search specific parties

4. **Generate and Export:**
   - Click "Generate" to create report
   - Use export buttons for Excel, PDF, or CSV
   - Download data for further analysis

### 3. GST Return Preparation
1. **Navigate to "GST Returns" section**
2. **Select Return Period:**
   - Use date picker to select month/quarter
   - Choose from preset periods

3. **Review Return Tabs:**
   - **GSTR-1**: Outward supplies (sales) impact
   - **GSTR-2**: Inward supplies (purchase) impact  
   - **GSTR-3B**: Overall tax liability summary

4. **Export Compliance Data:**
   - JSON format for GST portal upload
   - Excel format for manual processing
   - Print-ready reports for filing

### 4. Report Customization
1. **Dynamic Filtering:**
   - Real-time date range selection
   - Multi-level filtering options
   - Advanced search capabilities

2. **Grouping Options:**
   - By Date: Daily transaction summary
   - By Month: Monthly consolidation
   - By Party: Customer/Supplier wise
   - By GST Rate: Tax slab analysis

3. **Export Customization:**
   - Choose specific columns
   - Select data ranges
   - Format preferences

## 🔒 Security Features
- **SQL Injection Protection**: Prepared statements for all queries
- **XSS Protection**: Proper HTML encoding and validation
- **Input Validation**: Server-side validation for all inputs
- **Error Handling**: Graceful error management and logging

## 🌐 Browser Compatibility
- **Modern Browsers**: Chrome, Firefox, Safari, Edge (latest versions)
- **Mobile Responsive**: Optimized for tablets and smartphones
- **Progressive Enhancement**: Graceful degradation for older browsers
- **JavaScript Required**: Enhanced functionality with JS, basic operation without

## ⚡ Performance Features
- **Efficient Queries**: Optimized database queries with proper indexing
- **AJAX Loading**: Asynchronous report generation
- **Pagination**: Large dataset handling
- **Caching**: Optimized data retrieval
- **Lazy Loading**: On-demand content loading

## 🛠 Installation

### 1. Database Setup
```sql
-- Run the database creation script
mysql -u username -p database_name < database.sql
```

### 2. Configuration
```php
// Update config.php with your database settings
$db_config = [
    'host' => 'localhost',
    'username' => 'your_username', 
    'password' => 'your_password',
    'database' => 'billing_pos', // Your existing database
    'charset' => 'utf8mb4'
];
```

### 3. File Structure
```
GST_Notes/
├── index.php              # Main application with routing
├── config.php             # Database config and helper functions
├── database.sql           # Database schema and sample data
├── test_connection.php    # Database connection tester
├── README.md              # This documentation
└── pages/
    ├── dashboard.php       # Main dashboard with stats
    ├── credit_notes.php    # Credit notes CRUD
    ├── debit_notes.php     # Debit notes CRUD
    ├── reports.php         # Advanced reporting system
    └── gst_returns.php     # GST returns preparation
```

## 📋 Requirements

### System Requirements
- **PHP**: 7.4 or higher
- **MySQL**: 5.7 or higher  
- **Web Server**: Apache/Nginx
- **Extensions**: mysqli, json, mbstring

### Browser Requirements
- **JavaScript**: Required for advanced features
- **Cookies**: For session management
- **Local Storage**: For user preferences

### Dependencies (CDN)
- **Bootstrap 5.1.3**: UI framework
- **Font Awesome 6.0**: Icons
- **jQuery 3.6**: JavaScript library
- **Moment.js**: Date manipulation
- **DateRangePicker**: Advanced date selection

## 🚀 Future Enhancements

### Planned Features
- **API Integration**: REST API for third-party integration
- **Bulk Operations**: Import/Export of multiple notes
- **Email Integration**: Automated report delivery
- **Advanced Analytics**: Trends and insights
- **Audit Trail**: Complete change logging

### Integration Opportunities
- **E-Invoice System**: Direct integration with e-invoice APIs
- **ERP Systems**: Integration with popular ERP solutions
- **Accounting Software**: Data sync with Tally, QuickBooks
- **GST Portal**: Direct return filing capabilities

## 🆘 Troubleshooting

### Common Issues

**1. Database Connection Error**
```
- Check database credentials in config.php
- Ensure MySQL server is running
- Verify database name exists
```

**2. Reports Not Loading**
```
- Check JavaScript console for errors
- Verify AJAX endpoints are accessible
- Ensure proper file permissions
```

**3. Export Not Working**
```
- Check PHP memory limits
- Verify write permissions for temp files
- Ensure all required PHP extensions are loaded
```

**4. GST Calculations Wrong**
```
- Verify GST rates are entered correctly
- Check JavaScript calculation functions
- Ensure decimal precision is maintained
```

### Debug Mode
```php
// Enable error reporting in config.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
```

## 📞 Support

### Documentation
- Code comments throughout all files
- Database schema documentation
- Function-level documentation

### Resources
- Sample data included for testing
- Test connection utility provided
- Error logging for troubleshooting

## 📝 Version History

**Version 2.0** (Current)
- ✅ Advanced reporting system
- ✅ GST returns preparation
- ✅ Multiple export formats
- ✅ Enhanced UI/UX
- ✅ Mobile responsiveness

**Version 1.0** (Previous)
- ✅ Basic CRUD operations
- ✅ GST calculations
- ✅ Simple dashboard
- ✅ Basic search functionality

---

**© 2025 GST Notes Module - Advanced Reporting Edition**
