<?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;

    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;
    $status = 'Aprobado';

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

    $pdo->beginTransaction();

    $sql = "INSERT INTO projects (name, client_id, service_id, start_date, due_date, description, status) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    
    $stmt->execute([$name, $client_id, $service_id, $start_date, $due_date, $description, $status]);
    
    $new_project_id = $pdo->lastInsertId();

    $stmt_get = $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
        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_get->execute([$new_project_id]);
    $new_project = $stmt_get->fetch(PDO::FETCH_ASSOC);

    $new_project['client_name'] = trim($new_project['first_name'] . ' ' . $new_project['last_name']);
    unset($new_project['first_name'], $new_project['last_name']);

    $pdo->commit();

    $response = ['success' => true, 'message' => 'PROYECTO CREADO', 'project' => $new_project];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error PDO en projects-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error general en projects-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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