<?php
require_once 'config.php';

function getDB() {
    try {
        $pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch(PDOException $e) {
        die("Database connection failed: " . $e->getMessage());
    }
}

function generateDocNumber($type) {
    $prefix = '';
    switch($type) {
        case 'quotation': $prefix = 'Q'; break;
        case 'proforma': $prefix = 'PF'; break;
        case 'invoice': $prefix = 'INV'; break;
        case 'receipt': $prefix = 'RCP'; break;
        default: $prefix = 'DOC';
    }
    $year = date('Y');
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM documents WHERE doc_type = ? AND YEAR(doc_date) = ?");
    $stmt->execute([$type, $year]);
    $count = $stmt->fetchColumn() + 1;
    return $prefix . '-' . $year . '-' . str_pad($count, 3, '0', STR_PAD_LEFT);
}

function saveDocument($data) {
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO documents (doc_type, doc_number, doc_date, customer_name, customer_address, customer_phone, customer_email, items, subtotal, vat_amount, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $data['doc_type'],
        $data['doc_number'],
        $data['doc_date'],
        $data['customer_name'],
        $data['customer_address'],
        $data['customer_phone'],
        $data['customer_email'],
        json_encode($data['items']),
        $data['subtotal'],
        $data['vat_amount'],
        $data['total']
    ]);
    return $pdo->lastInsertId();
}

function getDocuments($search = '') {
    $pdo = getDB();
    $sql = "SELECT * FROM documents";
    if($search) {
        $sql .= " WHERE doc_number LIKE ? OR customer_name LIKE ? OR customer_address LIKE ?";
        $search = '%' . $search . '%';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$search, $search, $search]);
    } else {
        $stmt = $pdo->query($sql);
    }
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getDocument($id) {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}
?>