<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/nextcloud.php';
require_once __DIR__ . '/src/contract_file_helper.php';
require_login();

$pdo = get_db_connection();
$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? null;

function log_email_audit($pdo, $contract_id, $type, $desc) {
    $stmt = $pdo->prepare("INSERT INTO email_contract_history (contract_id, action_type, description, changed_by) VALUES (?, ?, ?, ?)");
    $stmt->execute([$contract_id, $type, $desc, $_SESSION['user_id']]);
}

switch ($action) {
    case 'create':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $company_name = $_POST['company_name'];
            $sender_email = $_POST['sender_email'];
            $unit_name = $_POST['unit_name'];
            $contract_number = $_POST['contract_number'];
            $priority = $_POST['priority'] ?: 'normal';
            
            // Inserir contrato
            $stmt = $pdo->prepare("INSERT INTO email_contracts (company_name, sender_email, unit_name, contract_number, priority, status, created_by) VALUES (?, ?, ?, ?, ?, 'Recebido', ?)");
            $stmt->execute([$company_name, $sender_email, $unit_name, $contract_number, $priority, $_SESSION['user_id']]);
            $contract_id = $pdo->lastInsertId();

            // Lidar com o arquivo inicial
            if (isset($_FILES['contract_file']) && $_FILES['contract_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['contract_file'];
                $fileName = time() . '_' . basename($file['name']);
                
                // Organizar pasta no Nextcloud
                $unitFolder = preg_replace('/[\/:*?"<>|]/', '_', $unit_name);
                $destRemotePath = cfh_build_remote_contract_path($unitFolder, $fileName);
                
                try {
                    $nc = new Nextcloud();
                    // Garantir que a pasta existe
                    $remoteRoot = trim(str_replace('\\', '/', (string)cfh_get_remote_contracts_root()), '/');
                    $nc->createFolder($remoteRoot . '/' . $unitFolder);
                    
                    if ($nc->uploadFile($file['tmp_name'], $destRemotePath)) {
                        // Salvar versão inicial
                        $stmtV = $pdo->prepare("INSERT INTO email_contract_versions (contract_id, version_number, version_label, file_path, file_name, created_by) VALUES (?, 1, 'v1', ?, ?, ?)");
                        $stmtV->execute([$contract_id, $destRemotePath, basename($file['name']), $_SESSION['user_id']]);
                        
                        // Registrar na timeline como mensagem de sistema
                        $stmtM = $pdo->prepare("INSERT INTO email_contract_messages (contract_id, direction, body_text, sender_name, sent_at) VALUES (?, 'outgoing', ?, ?, NOW())");
                        $stmtM->execute([$contract_id, "Processo iniciado manualmente com o arquivo: " . $file['name'], $_SESSION['username']]);
                        $msg_id = $pdo->lastInsertId();

                        // Salvar anexo vinculado à mensagem
                        $stmtA = $pdo->prepare("INSERT INTO email_contract_attachments (contract_id, message_id, original_name, stored_path, file_ext, mime_type, file_size) VALUES (?, ?, ?, ?, ?, ?, ?)");
                        $stmtA->execute([$contract_id, $msg_id, basename($file['name']), $destRemotePath, pathinfo($file['name'], PATHINFO_EXTENSION), $file['type'], $file['size']]);
                    }
                } catch (Exception $e) {
                    // Erro silencioso ou log
                }
            }

            log_email_audit($pdo, $contract_id, 'Criação', 'Novo processo manual criado');
            header('Location: email_contracts.php');
            exit;
        }
        break;

    case 'update_status':
        $new_status = $_GET['status'] ?? '';
        if ($id && $new_status) {
            $stmt = $pdo->prepare("SELECT status FROM email_contracts WHERE id = ?");
            $stmt->execute([$id]);
            $old_status = $stmt->fetchColumn();

            $is_locked = ($new_status === 'Assinado' || $new_status === 'Finalizado') ? 1 : 0;
            
            $stmt = $pdo->prepare("UPDATE email_contracts SET status = ?, is_locked = ? WHERE id = ?");
            $stmt->execute([$new_status, $is_locked, $id]);

            // Registrar na timeline
            $stmtM = $pdo->prepare("INSERT INTO email_contract_messages (contract_id, direction, body_text, sender_name, sent_at) VALUES (?, 'outgoing', ?, 'Sistema', NOW())");
            $stmtM->execute([$id, "Status alterado de '$old_status' para '$new_status'"]);

            log_email_audit($pdo, $id, 'Status', "Status alterado para $new_status");
            header("Location: email_contract_view.php?id=$id");
            exit;
        }
        break;

    case 'send_message':
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && $id) {
            $body = $_POST['message_body'];
            $is_new_version = isset($_POST['is_new_version']);
            
            // 1. Salvar mensagem no banco
            $stmt = $pdo->prepare("INSERT INTO email_contract_messages (contract_id, direction, body_text, sender_name, sent_at) VALUES (?, 'outgoing', ?, ?, NOW())");
            $stmt->execute([$id, $body, $_SESSION['username']]);
            $msg_id = $pdo->lastInsertId();

            // 2. Lidar com anexos
            if (!empty($_FILES['attachments']['name'][0])) {
                $nc = new Nextcloud();
                
                // Buscar unidade para pasta
                $stmtU = $pdo->prepare("SELECT unit_name FROM email_contracts WHERE id = ?");
                $stmtU->execute([$id]);
                $unit_name = $stmtU->fetchColumn();
                $unitFolder = preg_replace('/[\/:*?"<>|]/', '_', $unit_name);

                foreach ($_FILES['attachments']['name'] as $key => $name) {
                    if ($_FILES['attachments']['error'][$key] === UPLOAD_ERR_OK) {
                        $tmpPath = $_FILES['attachments']['tmp_name'][$key];
                        $originalName = basename($name);
                        $fileName = time() . '_' . $originalName;
                        $destRemotePath = cfh_build_remote_contract_path($unitFolder, $fileName);

                        try {
                            if ($nc->uploadFile($tmpPath, $destRemotePath)) {
                                // Salvar anexo
                                $stmtA = $pdo->prepare("INSERT INTO email_contract_attachments (contract_id, message_id, original_name, stored_path, file_ext, mime_type, file_size) VALUES (?, ?, ?, ?, ?, ?, ?)");
                                $stmtA->execute([$id, $msg_id, $originalName, $destRemotePath, pathinfo($name, PATHINFO_EXTENSION), $_FILES['attachments']['type'][$key], $_FILES['attachments']['size'][$key]]);
                                
                                // Se for nova versão
                                if ($is_new_version && strtolower(pathinfo($name, PATHINFO_EXTENSION)) === 'pdf') {
                                    $stmtVN = $pdo->prepare("SELECT MAX(version_number) FROM email_contract_versions WHERE contract_id = ?");
                                    $stmtVN->execute([$id]);
                                    $next_v = (int)$stmtVN->fetchColumn() + 1;

                                    $stmtV = $pdo->prepare("INSERT INTO email_contract_versions (contract_id, version_number, version_label, file_path, file_name, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                                    $stmtV->execute([$id, $next_v, 'v'.$next_v, $destRemotePath, $originalName, $_SESSION['user_id']]);
                                }
                            }
                        } catch (Exception $e) {}
                    }
                }
            }

            // 3. Atualizar data da última mensagem
            $pdo->prepare("UPDATE email_contracts SET last_message_at = NOW() WHERE id = ?")->execute([$id]);

            log_email_audit($pdo, $id, 'Mensagem', 'Resposta enviada pelo sistema');
            
            // TODO: Aqui entraria a lógica de envio real via SMTP/PHPMailer
            
            header("Location: email_contract_view.php?id=$id");
            exit;
        }
        break;

    case 'upload_version':
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && $id) {
            if (isset($_FILES['contract_file']) && $_FILES['contract_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['contract_file'];
                $label = $_POST['version_label'];
                
                // Buscar unidade
                $stmtU = $pdo->prepare("SELECT unit_name FROM email_contracts WHERE id = ?");
                $stmtU->execute([$id]);
                $unit_name = $stmtU->fetchColumn();
                $unitFolder = preg_replace('/[\/:*?"<>|]/', '_', $unit_name);

                $fileName = time() . '_' . basename($file['name']);
                $destRemotePath = cfh_build_remote_contract_path($unitFolder, $fileName);

                try {
                    $nc = new Nextcloud();
                    if ($nc->uploadFile($file['tmp_name'], $destRemotePath)) {
                        // Determinar número da versão
                        $stmtVN = $pdo->prepare("SELECT MAX(version_number) FROM email_contract_versions WHERE contract_id = ?");
                        $stmtVN->execute([$id]);
                        $next_v = (int)$stmtVN->fetchColumn() + 1;
                        
                        if (!$label) $label = 'v' . $next_v;

                        $stmtV = $pdo->prepare("INSERT INTO email_contract_versions (contract_id, version_number, version_label, file_path, file_name, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                        $stmtV->execute([$id, $next_v, $label, $destRemotePath, basename($file['name']), $_SESSION['user_id']]);
                        
                        // Registrar na timeline
                        $stmtM = $pdo->prepare("INSERT INTO email_contract_messages (contract_id, direction, body_text, sender_name, sent_at) VALUES (?, 'outgoing', ?, 'Sistema', NOW())");
                        $stmtM->execute([$id, "Nova versão enviada manualmente: $label (" . $file['name'] . ")"]);
                    }
                } catch (Exception $e) {}
            }
            
            log_email_audit($pdo, $id, 'Versão', "Upload manual de nova versão: $label");
            header("Location: email_contract_view.php?id=$id");
            exit;
        }
        break;

    case 'delete':
        if ($id) {
            // Buscar dados para excluir anexos físicos se necessário (opcional, vamos focar no DB)
            $stmt = $pdo->prepare("DELETE FROM email_contracts WHERE id = ?");
            if ($stmt->execute([$id])) {
                header("Location: email_contracts.php?msg=deleted");
            } else {
                header("Location: email_contracts.php?error=delete_failed");
            }
            exit;
        }
        break;

    case 'delete_message':
        $msg_id = $_GET['msg_id'] ?? null;
        if ($id && $msg_id) {
            $stmt = $pdo->prepare("SELECT id FROM email_contract_messages WHERE id = ? AND contract_id = ? LIMIT 1");
            $stmt->execute([$msg_id, $id]);
            if ($stmt->fetch()) {
                $pdo->prepare("DELETE FROM email_contract_attachments WHERE message_id = ?")->execute([$msg_id]);
                $pdo->prepare("DELETE FROM email_contract_messages WHERE id = ?")->execute([$msg_id]);

                log_email_audit($pdo, $id, 'Exclusão', "Mensagem removida (ID: $msg_id)");
            }

            header("Location: email_contract_view.php?id=$id");
            exit;
        }
        break;
}
