<?php
require_once __DIR__ . '/../includes/config.php';

$createdBy = requireAuth();
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("
                    SELECT sp.*, e.name as employee_name, a.name as created_by_name 
                    FROM salary_payments sp 
                    LEFT JOIN employees e ON sp.employee_id = e.id 
                    LEFT JOIN administrators a ON sp.created_by = a.id
                    WHERE sp.id = ?
                ");
                $stmt->execute([$_GET['id']]);
                $payment = $stmt->fetch();
                
                if ($payment) {
                    jsonResponse($payment);
                } else {
                    jsonResponse(['error' => 'Pagamento não encontrado'], 404);
                }
            } else {
                $employeeId = $_GET['employee_id'] ?? null;
                $referenceMonth = $_GET['reference_month'] ?? null;
                
                $sql = "
                    SELECT sp.*, e.name as employee_name, a.name as created_by_name 
                    FROM salary_payments sp 
                    LEFT JOIN employees e ON sp.employee_id = e.id 
                    LEFT JOIN administrators a ON sp.created_by = a.id
                ";
                $params = [];
                $conditions = [];
                
                if ($employeeId) {
                    $conditions[] = "sp.employee_id = ?";
                    $params[] = $employeeId;
                }
                
                if ($referenceMonth) {
                    $conditions[] = "sp.reference_month = ?";
                    $params[] = $referenceMonth;
                }
                
                if (!empty($conditions)) {
                    $sql .= " WHERE " . implode(" AND ", $conditions);
                }
                
                $sql .= " ORDER BY sp.payment_date DESC, sp.created_at DESC";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                jsonResponse($stmt->fetchAll());
            }
            break;

        case 'POST':
            $data = getJsonInput();
            
            if (empty($data['employee_id'])) {
                jsonResponse(['error' => 'Funcionário é obrigatório'], 400);
            }
            if (empty($data['amount']) || $data['amount'] <= 0) {
                jsonResponse(['error' => 'Valor é obrigatório e deve ser maior que zero'], 400);
            }
            
            // Get employee name for transaction description
            $stmt = $pdo->prepare("SELECT name, branch_id FROM employees WHERE id = ?");
            $stmt->execute([$data['employee_id']]);
            $employee = $stmt->fetch();
            
            // Get salary category ID
            $stmt = $pdo->prepare("SELECT id FROM categories WHERE name = 'Salários' AND type = 'expense' LIMIT 1");
            $stmt->execute();
            $salaryCategory = $stmt->fetch();
            $categoryId = $salaryCategory ? $salaryCategory['id'] : null;
            
            $pdo->beginTransaction();
            
            try {
                $id = generateId();
                $transactionId = generateId();
                $paymentType = $data['payment_type'] ?? 'salary';
                $paymentDate = $data['payment_date'] ?? date('Y-m-d');
                $description = $data['description'] ?? null;
                $amount = $data['amount'];
                
                // Create transaction (expense) for this payment
                $transactionDesc = $paymentType === 'advance' 
                    ? "Adiantamento - " . ($employee['name'] ?? 'Funcionário')
                    : "Salário - " . ($employee['name'] ?? 'Funcionário');
                
                if ($description) {
                    $transactionDesc .= " ($description)";
                }
                
                $stmt = $pdo->prepare("
                    INSERT INTO transactions (id, type, description, amount, transaction_date, payment_method, branch_id, category_id, status, notes, created_by)
                    VALUES (?, 'expense', ?, ?, ?, 'cash', ?, ?, 'completed', ?, ?)
                ");
                $stmt->execute([
                    $transactionId,
                    $transactionDesc,
                    $amount,
                    $paymentDate,
                    $employee['branch_id'] ?? null,
                    $categoryId,
                    "Pagamento de salário registrado automaticamente",
                    $createdBy
                ]);
                
                // Create salary payment linked to transaction
                $stmt = $pdo->prepare("
                    INSERT INTO salary_payments (id, employee_id, payment_type, amount, payment_date, reference_month, description, created_by, transaction_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $id,
                    $data['employee_id'],
                    $paymentType,
                    $amount,
                    $paymentDate,
                    $data['reference_month'] ?? date('Y-m'),
                    $description,
                    $createdBy,
                    $transactionId
                ]);
                
                $pdo->commit();
                
                $stmt = $pdo->prepare("
                    SELECT sp.*, e.name as employee_name 
                    FROM salary_payments sp 
                    LEFT JOIN employees e ON sp.employee_id = e.id 
                    WHERE sp.id = ?
                ");
                $stmt->execute([$id]);
                jsonResponse($stmt->fetch(), 201);
                
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'PUT':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $data = getJsonInput();
            
            if (empty($data['employee_id'])) {
                jsonResponse(['error' => 'Funcionário é obrigatório'], 400);
            }
            if (empty($data['amount']) || $data['amount'] <= 0) {
                jsonResponse(['error' => 'Valor é obrigatório e deve ser maior que zero'], 400);
            }
            
            // Get existing payment to find transaction_id
            $stmt = $pdo->prepare("SELECT transaction_id FROM salary_payments WHERE id = ?");
            $stmt->execute([$id]);
            $existingPayment = $stmt->fetch();
            
            // Get employee info
            $stmt = $pdo->prepare("SELECT name, branch_id FROM employees WHERE id = ?");
            $stmt->execute([$data['employee_id']]);
            $employee = $stmt->fetch();
            
            $pdo->beginTransaction();
            
            try {
                $paymentType = $data['payment_type'] ?? 'salary';
                $paymentDate = $data['payment_date'] ?? date('Y-m-d');
                $description = $data['description'] ?? null;
                $amount = $data['amount'];
                
                // Update the linked transaction if exists
                if ($existingPayment && $existingPayment['transaction_id']) {
                    $transactionDesc = $paymentType === 'advance' 
                        ? "Adiantamento - " . ($employee['name'] ?? 'Funcionário')
                        : "Salário - " . ($employee['name'] ?? 'Funcionário');
                    
                    if ($description) {
                        $transactionDesc .= " ($description)";
                    }
                    
                    $stmt = $pdo->prepare("
                        UPDATE transactions 
                        SET description = ?, amount = ?, transaction_date = ?, branch_id = ?
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $transactionDesc,
                        $amount,
                        $paymentDate,
                        $employee['branch_id'] ?? null,
                        $existingPayment['transaction_id']
                    ]);
                }
                
                // Update salary payment
                $stmt = $pdo->prepare("
                    UPDATE salary_payments 
                    SET employee_id = ?, payment_type = ?, amount = ?, payment_date = ?, reference_month = ?, description = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $data['employee_id'],
                    $paymentType,
                    $amount,
                    $paymentDate,
                    $data['reference_month'] ?? date('Y-m'),
                    $description,
                    $id
                ]);
                
                $pdo->commit();
                
                $stmt = $pdo->prepare("
                    SELECT sp.*, e.name as employee_name 
                    FROM salary_payments sp 
                    LEFT JOIN employees e ON sp.employee_id = e.id 
                    WHERE sp.id = ?
                ");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                
                if ($result) {
                    jsonResponse($result);
                } else {
                    jsonResponse(['error' => 'Pagamento não encontrado'], 404);
                }
                
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            // Get transaction_id before deleting
            $stmt = $pdo->prepare("SELECT transaction_id FROM salary_payments WHERE id = ?");
            $stmt->execute([$id]);
            $payment = $stmt->fetch();
            
            $pdo->beginTransaction();
            
            try {
                // Delete the salary payment
                $stmt = $pdo->prepare("DELETE FROM salary_payments WHERE id = ?");
                $stmt->execute([$id]);
                $deleted = $stmt->rowCount() > 0;
                
                // Delete the linked transaction if exists
                if ($deleted && $payment && $payment['transaction_id']) {
                    $stmt = $pdo->prepare("DELETE FROM transactions WHERE id = ?");
                    $stmt->execute([$payment['transaction_id']]);
                }
                
                $pdo->commit();
                
                if ($deleted) {
                    jsonResponse(['success' => true]);
                } else {
                    jsonResponse(['error' => 'Pagamento não encontrado'], 404);
                }
                
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        default:
            jsonResponse(['error' => 'Método não permitido'], 405);
    }
} catch (PDOException $e) {
    jsonResponse(['error' => 'Erro no banco de dados: ' . $e->getMessage()], 500);
}
