# Seder Core - Setup Guide

A complete PHP + MySQL stock & sales management application covering:
purchase vendors, sale customers, item master, purchase entry, stock tracking
(Available → Freeze → Sold), quotations with GST (9%+9%) and hidden discount
logic, delivery notes, tax invoices, automated customer emails, sale & manual
billing, and reports (Purchase, Sales, Cash Flow).

---

## 1. Requirements

- PHP 8.0+ (with PDO MySQL extension)
- MySQL 5.7+ / MariaDB 10.3+
- Composer (for PHPMailer - email automation)
- A web server (Apache/Nginx) or PHP's built-in server for testing

---

## 2. Installation Steps

### Step 1 — Upload files
Upload the entire `stockapp` folder to your server (e.g. `/var/www/html/stockapp`
or your hosting's `public_html/stockapp`).

### Step 2 — Create the database
Import the schema:

```bash
mysql -u root -p < database.sql
```

This creates the `stockapp` database with all tables, a default admin user,
and starter settings/categories.

### Step 3 — Configure database connection
Edit `config/database.php`:

```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'stockapp');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');
define('APP_URL', 'http://yourdomain.com/stockapp');  // update this!
```

**IMPORTANT:** `APP_URL` must match the actual folder URL — all sidebar links
and redirects use this.

### Step 4 — Install PHPMailer (for email automation)
From the `stockapp` folder:

```bash
composer require phpmailer/phpmailer
```

This creates a `vendor/` folder. Without it, the app still works fully —
emails will just fail gracefully with a message telling you to install
PHPMailer.

### Step 5 — Set folder permissions
```bash
chmod -R 755 stockapp
chmod -R 775 stockapp/uploads
```

### Step 6 — Login
Visit `http://yourdomain.com/stockapp/login.php`

**Default credentials:**
- Email: `admin@stockapp.com`
- Password: `admin123`

**Change this password immediately** via Settings → Change Password.

---

## 3. Configure Email (Quotation/Delivery/Invoice Auto-mail)

Go to **Settings → Email/SMTP Configuration** and enter your SMTP details.

### For Gmail:
1. Enable 2-Factor Authentication on your Google account
2. Go to Google Account → Security → App Passwords
3. Generate an app password for "Mail"
4. Use these settings:
   - SMTP Host: `smtp.gmail.com`
   - Port: `587`
   - Encryption: `TLS`
   - Username: your Gmail address
   - Password: the 16-character app password (not your normal password)
   - From Email: your Gmail address

### For other providers (Outlook, Zoho, custom SMTP):
Use the host/port/credentials provided by your email host.

---

## 4. How the Application Flow Works

### A. Setup Master Data
1. **Settings** — Enter your company name, address, GST number, logo info
2. **Purchase Vendors** — Add your suppliers
3. **Sale Customers** — Add customers (email + phone are required — used for
   automated mailing and delivery contact)
4. **Item Master** — Add products with sale price and GST% (default 18% =
   9% CGST + 9% SGST)

### B. Purchase Flow (adds stock)
1. Go to **Purchase Entry** → New Purchase
2. Select vendor, add line items with quantity and purchase price
3. On save, stock automatically increases in **Available** quantity
4. View live stock anytime in **Stock Overview** (Available / Freeze / Sold
   columns + full movement history per item)

### C. Sales Flow (Quotation → Delivery → Invoice → Payment)

**1. Create Quotation**
- Go to **Quotations** → New Quotation
- Select customer, add items (GST 9%+9% auto-applied)
- Enter a **Discount %** — this is INTERNAL ONLY
- The system calculates the final customer-facing total with discount baked
  into the per-item price — **the discount % and discount amount are NEVER
  shown on the customer document**, only the adjusted final amount
- Internal discount breakdown is visible only in the "Internal Details" panel
  (marked `no-print`, won't appear when printed/emailed)

**2. Send Quotation to Customer**
- Open the quotation → click **"Send to Customer"**
- Automatically emails the customer at their saved email address
- Status changes to "Sent"

**3. Customer Approval**
- Once customer confirms (via phone/email), click **"Mark Accepted"**
- This unlocks **"Create Delivery Note"**

**4. Create Delivery Note**
- System checks stock availability
- On creation: stock moves from **Available → Freeze (Reserved)**
- Click **"Send to Customer"** to email the delivery note

**5. Mark Delivered**
- Once goods physically delivered, click **"Mark Delivered"**
- This unlocks **"Generate Tax Invoice"**

**6. Generate & Send Tax Invoice**
- Click **"Generate Tax Invoice"** — creates the GST tax invoice using the
  final (discounted) amounts
- Click **"Send to Customer"** to email it

**7. Mark Payment Received**
- When customer pays, open the invoice → **"Mark Payment Received"**
- Choose: amount, payment date/time (manual selection), payment mode
- On **full payment**:
  - Invoice status → "Paid"
  - Stock automatically moves **Freeze → Sold**
  - Cash inflow recorded in Cash Flow report with date/time
- Partial payments are supported (status → "Partial") and stock remains
  in Freeze until fully paid

### D. Manual Billing (Services)
- Go to **Manual Billing** for service invoices not tied to stock items
  (e.g. repair service, AMC, labor charges)
- Same GST 9%+9%, email-send, and payment-marking features apply
- Does NOT affect stock quantities

### E. Reports
- **Purchase Reports** — item-wise, vendor-wise, date-wise purchase totals
  with GST breakdown, filterable by date range and vendor
- **Sales Reports** — customer-wise, item-wise, date-wise sales with GST,
  received vs outstanding amounts
- **Cash Flow Report** — inflow (customer payments) vs outflow (vendor
  payments), date-wise, with full transaction log

---

## 5. Stock State Model

Every item has 3 live quantities tracked in `stock_ledger`:

| State | Meaning | Triggered by |
|---|---|---|
| **Available** | Free to sell/quote | Purchase entry (+), Delivery note creation (−) |
| **Freeze** | Reserved for a pending delivery/payment | Delivery note created (+), Full payment received (−) |
| **Sold** | Completed transaction | Full payment received (+) |

Full audit trail of every movement is in `stock_movements`, viewable per-item
in **Stock Overview → click the history icon**.

---

## 6. Notes on Discount Logic (as requested)

- Staff enters a **discount %** when creating a quotation (internal field)
- System computes: `total_before_discount = subtotal + CGST(9%) + SGST(9%)`
- `discount_amount = total_before_discount × discount% / 100`
- `grand_total (sent to customer) = total_before_discount − discount_amount`
- This discount is distributed proportionally across line items so the
  **customer's PDF/email shows only adjusted per-item rates and a final
  total** — no mention of "discount" anywhere
- Internal staff can still see the original price, discount %, and discount
  amount in the "Internal Details" box on the quotation view page (hidden
  during print/PDF via `no-print` class)

---

## 7. Folder Structure

```
stockapp/
├── config/
│   ├── database.php       # DB connection settings - EDIT THIS
│   └── email.php           # Email placeholder defaults
├── includes/
│   ├── functions.php       # Core helpers (stock logic, formatters, auth)
│   ├── Mailer.php           # PHPMailer wrapper + email templates
│   ├── header.php           # Sidebar + topbar layout
│   └── footer.php
├── modules/
│   ├── vendors/             # Purchase vendors & sale customers CRUD
│   ├── stock/               # Item master, purchase entry, stock overview
│   ├── quotation/            # Quotation create/view/email
│   ├── delivery/             # Delivery note create/view/email
│   ├── invoice/              # Tax invoice create/view/email/payment
│   ├── billing/              # Sale billing list + manual billing
│   ├── reports/              # Purchase/Sales/CashFlow reports
│   └── settings.php
├── assets/css/style.css      # Design system
├── uploads/                   # PDF attachments (optional, auto-created)
├── database.sql               # Full schema + seed data
├── composer.json              # PHPMailer dependency
├── login.php / logout.php
├── dashboard.php
└── index.php
```

---

## 8. Security Notes

- All forms use CSRF tokens
- Passwords hashed with `password_hash()` / bcrypt
- All output escaped via `sanitize()` (htmlspecialchars)
- Prepared statements (PDO) used throughout — no raw SQL concatenation
- **Change the default admin password immediately after first login**
- Consider enabling HTTPS for production (especially since SMTP credentials
  and customer data are involved)

---

## 9. Optional Enhancements (Future)

- PDF generation library (e.g. mPDF or DomPDF) for proper attached PDFs in
  emails — currently emails reference a PDF path; integrate a PDF library
  and save to `/uploads/quotation_XXX.pdf` etc. before sending
- Role-based permissions (currently single admin/staff role field exists but
  isn't enforced per-module)
- Multi-warehouse stock tracking
- Barcode/QR support for items
