# Antigravity: Patron Project Context & DB Class Guide

This document serves as a reference for Antigravity when working on the **Patron** project.

## 🔗 Project Context
- **Name**: Patron (Export Tracking System)
- **Version**: 1.0
- **Platform**: Web (PHP/PDO) & Mobile (Flutter)
- **Primary Goal**: Track export sales, maturities, and collections with role-based visibility.

## 💾 Database Access Layer
We use the singleton `DB` class from [phpr.org](https://www.phpr.org/pdo-mysql-veritabani-sinifi/).

### Usage Patterns

#### 1. Fetching Multiple Rows
```php
$rows = DB::get("SELECT * FROM customers WHERE is_active = 1");
foreach ($rows as $row) {
    echo $row->company_name; // Result is an object
}
```

#### 2. Fetching a Single Row
```php
$id = 5;
$customer = DB::getRow("SELECT * FROM customers WHERE id = ?", [$id]);
if ($customer) {
    echo $customer->company_name;
}
```

#### 3. Fetching a Single Variable
```php
$total = DB::getVar("SELECT SUM(amount) FROM sales WHERE currency = ?", ['USD']);
```

#### 4. Executing Commands (Insert/Update/Delete)
```php
// Insert returns Last Insert ID
$newId = DB::insert("INSERT INTO users (name, email) VALUES (?, ?)", [$name, $email]);

// Update/Delete returns affected rows count
$affected = DB::exec("UPDATE sales SET status = 'paid' WHERE id = ?", [$saleId]);
```

#### 5. Error Handling
```php
if ($error = DB::getLastError()) {
    // Log or display: $error[2]
}
```

## 🏗️ Architectural Rules
1. **Always use Prepared Statements**: Use `?` placeholders and pass parameters as an array.
2. **Role Filtering**: 
   - `exporter`: Always filter by `exporter_user_id`.
   - `operation`: Always filter by `operation_user_id`.
   - `admin/finance`: Full access.
3. **Maturity (Due Date)**: Always calculate as `sale_date + payment_term_days` unless manually overridden.
4. **Currency Handling**: Keep USD and EUR separate in all totals. Do NOT mix them without a conversion rate (v1 doesn't have conversion).

## 📁 File Structure
- `/config/db.php`: Contains the `DB` class.
- `/config/config.php`: DB credentials and constants.
- `/api/v1/`: REST endpoints.
- `/panel/`: Web view files.
