<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/api_auth.php';

function respond(array $data, int $code = 200): void
{
    http_response_code($code);
    echo json_encode($data);
    exit;
}

function request_payload(): array
{
    $raw = file_get_contents('php://input');
    if (!$raw) {
        return $_POST ?: [];
    }

    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        return $decoded;
    }

    parse_str($raw, $parsed);
    return is_array($parsed) ? $parsed : [];
}

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare("SHOW TABLES LIKE ?");
    $stmt->execute([$table]);
    return (bool)$stmt->fetchColumn();
}

function column_exists(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");
    $stmt->execute([$table, $column]);
    return (int)$stmt->fetchColumn() > 0;
}

function ensure_tables(PDO $pdo): void
{
    if (!table_exists($pdo, 'daily_entries')) {
        $pdo->exec("
            CREATE TABLE daily_entries (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                family_id INT UNSIGNED NOT NULL DEFAULT 0,
                client_id INT UNSIGNED NOT NULL,
                entry_date DATE NOT NULL,
                caregiver_name VARCHAR(255) NOT NULL DEFAULT '',
                journal_notes MEDIUMTEXT NULL,
                signature_data LONGTEXT NULL,
                payload_json LONGTEXT NULL,
                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY idx_family_client_date (family_id, client_id, entry_date),
                KEY idx_client_date (client_id, entry_date)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } else {
        if (!column_exists($pdo, 'daily_entries', 'family_id')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN family_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER id");
        }
        if (!column_exists($pdo, 'daily_entries', 'client_id')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN client_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER family_id");
        }
        if (!column_exists($pdo, 'daily_entries', 'entry_date')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN entry_date DATE NULL AFTER client_id");
        }
        if (!column_exists($pdo, 'daily_entries', 'caregiver_name')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN caregiver_name VARCHAR(255) NOT NULL DEFAULT '' AFTER entry_date");
        }
        if (!column_exists($pdo, 'daily_entries', 'journal_notes')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN journal_notes MEDIUMTEXT NULL AFTER caregiver_name");
        }
        if (!column_exists($pdo, 'daily_entries', 'signature_data')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN signature_data LONGTEXT NULL AFTER journal_notes");
        }
        if (!column_exists($pdo, 'daily_entries', 'payload_json')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN payload_json LONGTEXT NULL AFTER signature_data");
        }
        if (!column_exists($pdo, 'daily_entries', 'created_at')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER payload_json");
        }
        if (!column_exists($pdo, 'daily_entries', 'updated_at')) {
            $pdo->exec("ALTER TABLE daily_entries ADD COLUMN updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at");
        }
    }

    if (!table_exists($pdo, 'daily_entry_tasks')) {
        $pdo->exec("
            CREATE TABLE daily_entry_tasks (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT,
                entry_id INT UNSIGNED NOT NULL,
                family_id INT UNSIGNED NOT NULL DEFAULT 0,
                client_id INT UNSIGNED NOT NULL DEFAULT 0,
                task_time VARCHAR(32) NOT NULL DEFAULT '',
                task_type VARCHAR(255) NOT NULL DEFAULT '',
                details TEXT NULL,
                completed TINYINT(1) NOT NULL DEFAULT 0,
                sort_order INT NOT NULL DEFAULT 0,
                created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY idx_entry_id (entry_id),
                KEY idx_family_client (family_id, client_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } else {
        if (!column_exists($pdo, 'daily_entry_tasks', 'entry_id')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN entry_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER id");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'family_id')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN family_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER entry_id");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'client_id')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN client_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER family_id");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'task_time')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN task_time VARCHAR(32) NOT NULL DEFAULT '' AFTER client_id");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'task_type')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN task_type VARCHAR(255) NOT NULL DEFAULT '' AFTER task_time");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'details')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN details TEXT NULL AFTER task_type");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'completed')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN completed TINYINT(1) NOT NULL DEFAULT 0 AFTER details");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'sort_order')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN sort_order INT NOT NULL DEFAULT 0 AFTER completed");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'created_at')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER sort_order");
        }
        if (!column_exists($pdo, 'daily_entry_tasks', 'updated_at')) {
            $pdo->exec("ALTER TABLE daily_entry_tasks ADD COLUMN updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at");
        }
    }
}

function normalize_tasks($tasks): array
{
    if (is_string($tasks) && $tasks !== '') {
        $decoded = json_decode($tasks, true);
        if (is_array($decoded)) {
            $tasks = $decoded;
        }
    }

    if (!is_array($tasks)) {
        return [];
    }

    $normalized = [];
    $i = 0;

    foreach ($tasks as $task) {
        if (!is_array($task)) {
            continue;
        }

        $normalized[] = [
            'time' => trim((string)($task['time'] ?? '')),
            'task_type' => trim((string)($task['task_type'] ?? $task['type'] ?? '')),
            'details' => trim((string)($task['details'] ?? '')),
            'completed' => !empty($task['completed']) ? 1 : 0,
            'sort_order' => isset($task['sort_order']) ? (int)$task['sort_order'] : $i
        ];
        $i++;
    }

    return $normalized;
}

try {
    $session = require_family_session();
    $familyId = (int)($session['family_id'] ?? 0);

    if ($familyId <= 0) {
        respond([
            'success' => false,
            'message' => 'Family session required.'
        ], 403);
    }

    $pdo = db();
    ensure_tables($pdo);

    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $action = $_REQUEST['action'] ?? '';

    if ($method === 'GET') {
        $clientId = (int)($_GET['client_id'] ?? 0);

        if ($clientId <= 0) {
            respond(['success' => false, 'message' => 'client_id required'], 400);
        }

        $stmt = $pdo->prepare("
            SELECT id, family_id, client_id, entry_date, caregiver_name, journal_notes, signature_data, payload_json, created_at, updated_at
            FROM daily_entries
            WHERE family_id = ? AND client_id = ?
            ORDER BY entry_date DESC, id DESC
        ");
        $stmt->execute([$familyId, $clientId]);
        $entries = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $taskStmt = $pdo->prepare("
            SELECT entry_id, task_time, task_type, details, completed, sort_order
            FROM daily_entry_tasks
            WHERE family_id = ? AND client_id = ?
            ORDER BY entry_id ASC, sort_order ASC, id ASC
        ");
        $taskStmt->execute([$familyId, $clientId]);
        $taskRows = $taskStmt->fetchAll(PDO::FETCH_ASSOC);

        $tasksByEntry = [];
        foreach ($taskRows as $row) {
            $eid = (int)$row['entry_id'];
            if (!isset($tasksByEntry[$eid])) {
                $tasksByEntry[$eid] = [];
            }

            $tasksByEntry[$eid][] = [
                'time' => $row['task_time'] ?? '',
                'type' => $row['task_type'] ?? '',
                'task_type' => $row['task_type'] ?? '',
                'details' => $row['details'] ?? '',
                'completed' => (int)($row['completed'] ?? 0) === 1,
                'sort_order' => (int)($row['sort_order'] ?? 0)
            ];
        }

        $out = [];
        foreach ($entries as $row) {
            $payload = [];
            if (!empty($row['payload_json'])) {
                $decoded = json_decode((string)$row['payload_json'], true);
                if (is_array($decoded)) {
                    $payload = $decoded;
                }
            }

            $entryId = (int)$row['id'];
            $out[] = [
                'id' => $entryId,
                'family_id' => (int)$row['family_id'],
                'client_id' => (int)$row['client_id'],
                'client_name' => $payload['client_name'] ?? '',
                'entry_date' => $row['entry_date'],
                'caregiver_name' => $row['caregiver_name'] ?? '',
                'daily_notes' => $row['journal_notes'] ?? '',
                'journal_notes' => $row['journal_notes'] ?? '',
                'signature_data_url' => $row['signature_data'] ?? '',
                'signature_data' => $row['signature_data'] ?? '',
                'medications' => is_array($payload['medications'] ?? null) ? $payload['medications'] : [],
                'tasks' => $tasksByEntry[$entryId] ?? [],
                'payload' => $payload,
                'created_at' => $row['created_at'] ?? null,
                'updated_at' => $row['updated_at'] ?? null
            ];
        }

        respond([
            'success' => true,
            'entries' => $out
        ]);
    }

    if ($method === 'POST') {
        $data = request_payload();
        $action = (string)($data['action'] ?? $action);

        if ($action === 'delete') {
            $id = (int)($data['id'] ?? 0);

            if ($id <= 0) {
                respond(['success' => false, 'message' => 'id required'], 400);
            }

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("DELETE FROM daily_entry_tasks WHERE entry_id = ? AND family_id = ?");
            $stmt->execute([$id, $familyId]);

            $stmt = $pdo->prepare("DELETE FROM daily_entries WHERE id = ? AND family_id = ?");
            $stmt->execute([$id, $familyId]);

            $pdo->commit();

            respond([
                'success' => true,
                'message' => 'Entry deleted'
            ]);
        }

        $clientId = (int)($data['client_id'] ?? 0);
        $entryDate = trim((string)($data['entry_date'] ?? $data['date'] ?? ''));
        $caregiverName = trim((string)($data['caregiver_name'] ?? ''));
        $journalNotes = trim((string)($data['daily_notes'] ?? $data['journal_notes'] ?? $data['notes'] ?? ''));
        $signatureData = trim((string)($data['signature_data_url'] ?? $data['signature_data'] ?? $data['signature'] ?? ''));
        $tasks = normalize_tasks($data['tasks'] ?? []);

        if ($clientId <= 0) {
            respond(['success' => false, 'message' => 'client_id required'], 400);
        }
        if ($entryDate === '') {
            respond(['success' => false, 'message' => 'entry_date required'], 400);
        }

        $entryId = (int)($data['id'] ?? 0);

        $payload = $data;
        unset($payload['tasks']);
        $payloadJson = json_encode($payload);

        $pdo->beginTransaction();

        if ($entryId > 0) {
            $stmt = $pdo->prepare("
                UPDATE daily_entries
                SET
                    entry_date = ?,
                    caregiver_name = ?,
                    journal_notes = ?,
                    signature_data = ?,
                    payload_json = ?,
                    updated_at = NOW()
                WHERE id = ? AND family_id = ?
            ");
            $stmt->execute([
                $entryDate,
                $caregiverName,
                $journalNotes,
                $signatureData,
                $payloadJson,
                $entryId,
                $familyId
            ]);
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO daily_entries
                    (family_id, client_id, entry_date, caregiver_name, journal_notes, signature_data, payload_json, created_at, updated_at)
                VALUES
                    (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            $stmt->execute([
                $familyId,
                $clientId,
                $entryDate,
                $caregiverName,
                $journalNotes,
                $signatureData,
                $payloadJson
            ]);
            $entryId = (int)$pdo->lastInsertId();
        }

        $stmt = $pdo->prepare("DELETE FROM daily_entry_tasks WHERE entry_id = ? AND family_id = ?");
        $stmt->execute([$entryId, $familyId]);

        if (!empty($tasks)) {
            $stmt = $pdo->prepare("
                INSERT INTO daily_entry_tasks
                    (entry_id, family_id, client_id, task_time, task_type, details, completed, sort_order, created_at, updated_at)
                VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            foreach ($tasks as $task) {
                $stmt->execute([
                    $entryId,
                    $familyId,
                    $clientId,
                    $task['time'],
                    $task['task_type'],
                    $task['details'],
                    $task['completed'],
                    $task['sort_order']
                ]);
            }
        }

        $pdo->commit();

        respond([
            'success' => true,
            'message' => 'Entry saved',
            'entry_id' => $entryId
        ]);
    }

    respond(['success' => false, 'message' => 'method not allowed'], 405);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    error_log('daily_entries.php error: ' . $e->getMessage());

    respond([
        'success' => false,
        'message' => 'server error',
        'error' => $e->getMessage()
    ], 500);
}