# Fortunes Solar Quotation System

## Overview
The **Fortunes Solar Quotation System** is an enterprise-grade SaaS application designed specifically for solar engineering and installation companies. It streamlines the complex process of generating, calculating, and managing commercial and residential solar system quotations. 

Built with performance, security, and a premium user experience in mind, the system handles complex calculations—including import costs, local taxation, energy yields, and ROI (Return on Investment)—all in real-time.

---

## 🌟 Key Features

### 1. Advanced Quotation Engine
- **Multiple System Types:** Supports On-Grid, Off-Grid, Hybrid, and Solar Water Pumping systems.
- **Dynamic Calculation Methods:** Depending on the system type, calculations are driven by Peak Load, Load Calculation, Monthly Electricity Bill, or Water Pumping Requirements.
- **Smart Pre-filling:** Automatically loads standard required materials (Inverters, PV Panels, DC Cables, Structure, etc.) based on the selected system type.
- **Real-time Calculations:** Instant mathematical updates for totals, sub-totals, VAT, AIT (Advance Income Tax), discounts, and margins without page reloads.

### 2. Comprehensive Import & Costing Module
- **Dual Part Costing:** Separates "Imported Materials" (calculated in USD with FOB rates, Freight, Insurance, L/C Fees) and "Local Materials/Works" (calculated in BDT).
- **Automated Conversions:** Applies live dollar conversion rates to seamlessly merge import and local costs.
- **Taxation & Margins:** Applies variable AIT and VAT percentages, along with customizable profit margins, to arrive at the final quotation amount.
- **Cost Analytics:** Automatically computes the *Cost per Watt* and *Cost per kW* (both including and excluding taxes).

### 3. Environmental & ROI Analytics
- **Energy Generation:** Estimates the Annual Energy Generated (kWh/year).
- **Green Impact:** Calculates Carbon Emission Reduction (kg CO2/year) and Coal Consumption Reduction.
- **Financial ROI:** Projects the estimated Payback Period (in years) based on system cost and energy savings.

### 4. Professional Document Generation
- **Print & PDF Engine:** Highly optimized A4-ready CSS ensures beautiful, clean, and professional printed documents.
- **Customer Quotation:** A clean, branded proposal showing final totals, warranties, terms, and environmental impact (hides sensitive internal margins).
- **Internal Costing View:** A detailed administrative printout showing exact profit margins, import breakdowns, and internal cost-per-watt metrics.

### 5. Enterprise UI/UX
- **Responsive Design:** A fully responsive, modern interface. Tables automatically convert to highly readable "Cards" on mobile devices.
- **Collapsible Sidebar:** Maximizes screen real estate on desktop for complex data entry.
- **Performance Optimized:** Uses Vanilla JavaScript and `requestAnimationFrame` for buttery-smooth form updates even with dozens of quotation rows.

---

## 🏗️ System Architecture & Tech Stack

The system is designed to be lightweight, incredibly fast, and easy to deploy without heavy dependencies.

- **Backend:** PHP 8+
- **Database:** SQLite (via PDO). Requires zero database server configuration and is highly portable.
- **Frontend Logic:** Vanilla JavaScript (`app.js`). No heavy frameworks (React/Vue) were used, ensuring lightning-fast load times.
- **Styling:** Custom Vanilla CSS (`app.css`) with CSS Variables for theming. Bootstrap 5 is utilized strictly for its grid system and utility classes.
- **Security:** Strict Content Security Policies (CSP) with cryptographic nonces, HttpOnly cookies, prepared SQL statements to prevent SQL injection, and robust XSS sanitization (`e()` helper function).

---

## 📂 Directory Structure

```text
Fortunes_Quotation/
├── app/
│   ├── config/
│   │   └── database.php       # SQLite PDO Connection
│   ├── data/
│   │   └── database.sqlite    # The Database File
│   └── includes/
│       ├── auth.php           # Session management & access control
│       ├── helpers.php        # Utility functions (db, e, money, flash)
│       ├── header.php         # Topbar, CSP Headers, and CSS imports
│       ├── sidebar.php        # Application navigation
│       └── footer.php         # JS scripts and closing tags
├── public/
│   ├── index.php              # App Entry point (Redirects)
│   ├── login.php              # Secure Authentication
│   ├── dashboard.php          # Analytics and high-level metrics
│   ├── profile.php            # User account settings
│   ├── assets/                # JS, CSS, and Images
│   ├── customers/             # Customer Management CRUD
│   └── quotations/
│       ├── create.php         # New Quotation Page
│       ├── edit.php           # Edit existing quotation
│       ├── view.php           # Detailed summary view
│       ├── print.php          # Print generation (Internal vs Customer)
│       ├── download.php       # PDF output trigger
│       └── form.php           # The core UI form (included by create/edit)
```

---

## ⚙️ How it Works: The Workflow

1. **Authentication:** Users log in securely via `login.php`. Access controls restrict 'Internal Costing' views to Admin/Sales roles.
2. **Customer Selection:** When starting a quotation, a user either selects an existing customer from the database or creates a new one inline.
3. **System Configuration:** The user selects the System Type (e.g., On-Grid). This triggers JavaScript to swap the dropdown calculation methods and instantly loads the corresponding default Bill of Quantities (BOQ).
4. **Data Entry:**
   - **Load Calculation:** Users input the appliances, watt ratings, and desired backup hours.
   - **Imported Materials:** If enabled, users specify items coming via Letter of Credit (L/C).
   - **Local Works:** Cables, installation fees, and structure costs are added.
5. **Real-Time Processing:** As the user types, `calcAll()` in `app.js` runs a debounced calculation pass. It aggregates all rows, computes the L/C fees, applies the dollar conversion, calculates VAT/AIT, and updates the grand total on screen.
6. **Save & Render:** Upon submission, the data is normalized and saved across multiple normalized SQLite tables (`quotations`, `quotation_items`, `quotation_loads`, `quotation_import_items`).
7. **Delivery:** The user navigates to the View page and clicks **Print Customer Quotation**, triggering a beautiful, browser-native print dialog perfectly scaled for A4 paper.

---

## 🛡️ Security Measures

- **No Hardcoded Credentials:** The system validates against securely hashed passwords in the SQLite database.
- **CSP & Headers:** Implements `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, and a strict `Content-Security-Policy` to mitigate modern web vulnerabilities.
- **Sanitized Outputs:** Every piece of user-generated content rendered to the screen is wrapped in the `e()` function (`htmlspecialchars`) to prevent Cross-Site Scripting (XSS).
