<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    session_start();
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    if (!isset($_SESSION['user_id'])) {
        throw new Exception('ACCESO NO AUTORIZADO');
    }

    $data = $_POST;
    $action = $data['action'] ?? '';
    $projectId = isset($data['id']) ? filter_var($data['id'], FILTER_VALIDATE_INT) : 0;

    if ($projectId === false || $projectId === 0) {
        throw new Exception('ID PROYECTO REQUERIDO');
    }

    function getUpdatedProject($pdo, $id) {
        $stmt = $pdo->prepare("
            SELECT p.id, p.name, p.description, p.start_date, p.due_date, p.status, p.updated_at, c.first_name, c.last_name, p.client_id, s.name as service_name, s.id as service_id
            FROM projects p
            JOIN clients c ON p.client_id = c.id
            LEFT JOIN services s ON p.service_id = s.id
            WHERE p.id = ?
        ");
        $stmt->execute([$id]);
        $project = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($project) {
            $project['client_name'] = trim($project['first_name'] . ' ' . $project['last_name']);
            unset($project['first_name'], $project['last_name']);
        }
        return $project;
    }

    switch ($action) {
        case 'edit_details':
            if (empty($data['name']) || empty($data['client_id']) || empty($data['service_id']) || empty($data['start_date'])) {
                throw new Exception('DATOS OBLIGATORIOS FALTANTES');
            }
            $name = filter_var(trim($data['name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $client_id = filter_var($data['client_id'], FILTER_VALIDATE_INT);
            $service_id = filter_var($data['service_id'], FILTER_VALIDATE_INT);
            $start_date = filter_var($data['start_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $due_date = !empty($data['due_date']) ? filter_var($data['due_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
            $description = !empty($data['description']) ? filter_var(trim($data['description']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

            if ($client_id === false || $service_id === false) {
                 throw new Exception('ID CLIENTE O SERVICIO INVALIDO');
            }

            try {
                $sql = "UPDATE projects SET name = ?, client_id = ?, service_id = ?, start_date = ?, due_date = ?, description = ? WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$name, $client_id, $service_id, $start_date, $due_date, $description, $projectId]);

                $updated_project = getUpdatedProject($pdo, $projectId);
                if ($updated_project) {
                    $response = ['success' => true, 'message' => 'PROYECTO ACTUALIZADO', 'project' => $updated_project];
                } else {
                    $response = ['success' => false, 'message' => 'PROYECTO NO ENCONTRADO'];
                }
            } catch (PDOException $e) {
                error_log("Error en projects-update.php (edit_details): " . $e->getMessage());
                $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
            }
            break;

        case 'update_status':
            if (!isset($data['status'])) {
                throw new Exception('ESTADO REQUERIDO');
            }
            $newStatus = trim($data['status']);
            $allowed_statuses = ['Aprobado', 'En Planificación', 'En Proceso', 'Listo para Revisión', 'Esperando Aprobación', 'Completado', 'Archivado'];
            if (!in_array($newStatus, $allowed_statuses)) {
                throw new Exception('ESTADO INVALIDO');
            }

            try {
                $sql = "UPDATE projects SET status = ? WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$newStatus, $projectId]);

                if ($stmt->rowCount() > 0) {
                    $updated_project = getUpdatedProject($pdo, $projectId);
                    if ($updated_project) {
                        $response = ['success' => true, 'message' => 'ESTADO ACTUALIZADO', 'project' => $updated_project];
                    } else {
                         $response = ['success' => true, 'message' => 'PROYECTO NO RECUPERADO'];
                    }
                } else {
                    $response = ['success' => true, 'message' => 'SIN CAMBIOS'];
                }
            } catch (PDOException $e) {
                error_log("Error en projects-update.php (update_status): " . $e->getMessage());
                $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
            }
            break;

        default:
            throw new Exception('ACCION INVALIDA');
            break;
    }
} catch (PDOException $e) {
    error_log("Error PDO en projects-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("Error general en projects-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>