<?php
/**
 * Document Management Class
 */

class Document {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Create a new document from template
     */
    public function create($user_id, $template_id, $document_type, $customer_data, $document_fields) {
        try {
            $document_data = json_encode($document_fields);
            $document_hash = hash('sha256', $document_data . time() . rand());

            $stmt = $this->pdo->prepare("
                INSERT INTO documents (
                    user_id, template_id, document_type, customer_name, customer_email,
                    customer_phone, vehicle_info, document_data, status, created_ip, document_hash
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending_signature', ?, ?)
            ");

            $vehicle_info = isset($customer_data['vehicle_year']) ?
                $customer_data['vehicle_year'] . ' ' . ($customer_data['vehicle_make'] ?? '') . ' ' . ($customer_data['vehicle_model'] ?? '') : '';

            $result = $stmt->execute([
                $user_id,
                $template_id ?: null,
                $document_type,
                $customer_data['customer_name'] ?? '',
                $customer_data['customer_email'] ?? '',
                $customer_data['customer_phone'] ?? null,
                $vehicle_info,
                $document_data,
                get_client_ip()
            ]);

            $document_id = $this->pdo->lastInsertId();
            log_action($user_id, $document_id, 'DOCUMENT_CREATED', "Type: $document_type");

            return ['success' => true, 'document_id' => $document_id];
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Get document by ID
     */
    public function get($document_id, $user_id = null) {
        try {
            $query = "SELECT * FROM documents WHERE id = ?";
            $params = [$document_id];

            if ($user_id) {
                $query .= " AND user_id = ?";
                $params[] = $user_id;
            }

            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);
            $document = $stmt->fetch();

            if ($document) {
                $document['document_data'] = json_decode($document['document_data'], true);
                $document['signatures'] = $this->getSignatures($document_id);
            }

            return $document;
        } catch (Exception $e) {
            return null;
        }
    }

    /**
     * Get all documents for user
     */
    public function getByUser($user_id, $status = null, $limit = 50, $offset = 0) {
        try {
            $query = "SELECT * FROM documents WHERE user_id = ?";
            $params = [$user_id];

            if ($status) {
                $query .= " AND status = ?";
                $params[] = $status;
            }

            $query .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;

            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetchAll();
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Update document status
     */
    public function updateStatus($document_id, $status, $user_id = null) {
        try {
            $query = "UPDATE documents SET status = ? WHERE id = ?";
            $params = [$status, $document_id];

            if ($user_id) {
                $query .= " AND user_id = ?";
                $params[] = $user_id;
            }

            $stmt = $this->pdo->prepare($query);
            $result = $stmt->execute($params);

            if ($result) {
                log_action($user_id, $document_id, 'STATUS_CHANGED', "New status: $status");
            }

            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Add signature to document
     */
    public function addSignature($document_id, $signature_data, $signer_name, $signer_email, $signer_role = 'customer') {
        try {
            $signature_hash = hash_signature($signature_data);

            $stmt = $this->pdo->prepare("
                INSERT INTO signatures (
                    document_id, signer_name, signer_email, signer_role, signature_data,
                    signature_hash, signer_ip, device_info
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $result = $stmt->execute([
                $document_id,
                $signer_name,
                $signer_email,
                $signer_role,
                $signature_data,
                $signature_hash,
                get_client_ip(),
                get_user_agent()
            ]);

            if ($result) {
                $this->updateStatus($document_id, 'signed');
                log_action(null, $document_id, 'DOCUMENT_SIGNED', "Signer: $signer_name ($signer_role)");
            }

            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get signatures for document
     */
    public function getSignatures($document_id) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT id, signer_name, signer_email, signer_role, signature_timestamp, signer_ip
                FROM signatures
                WHERE document_id = ?
                ORDER BY signature_timestamp ASC
            ");
            $stmt->execute([$document_id]);
            return $stmt->fetchAll();
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Get signature by ID (for PDF generation)
     */
    public function getSignatureData($signature_id) {
        try {
            $stmt = $this->pdo->prepare("SELECT signature_data FROM signatures WHERE id = ?");
            $stmt->execute([$signature_id]);
            $result = $stmt->fetch();
            return $result ? $result['signature_data'] : null;
        } catch (Exception $e) {
            return null;
        }
    }

    /**
     * Save PDF path to document
     */
    public function savePdfPath($document_id, $pdf_path) {
        try {
            $stmt = $this->pdo->prepare("UPDATE documents SET pdf_path = ?, signed_at = NOW(), signed_ip = ? WHERE id = ?");
            return $stmt->execute([$pdf_path, get_client_ip(), $document_id]);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get document count statistics
     */
    public function getStats($user_id) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'signed' THEN 1 ELSE 0 END) as signed,
                    SUM(CASE WHEN status = 'pending_signature' THEN 1 ELSE 0 END) as pending,
                    SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) as draft
                FROM documents
                WHERE user_id = ?
            ");
            $stmt->execute([$user_id]);
            return $stmt->fetch();
        } catch (Exception $e) {
            return null;
        }
    }
}
