<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// Ensure account_code is nullable and unique key removed
$mysqli->query("ALTER TABLE account_heads MODIFY COLUMN account_code VARCHAR(20) DEFAULT NULL");
try { $mysqli->query("ALTER TABLE account_heads DROP INDEX account_code"); } catch (Exception $e) { /* already dropped */ }

// Valid account types matching the existing enum
$validTypes = ['Asset', 'Liability', 'Income', 'Expense', 'Equity'];

switch ($action) {
    case 'list':
        $activeOnly  = isset($_GET['active_only']) ? (int)$_GET['active_only'] : 1;
        $parentOnly  = isset($_GET['parent_only']) ? (int)$_GET['parent_only'] : 0; // only top-level
        $parentId    = isset($_GET['parent_id'])   ? (int)$_GET['parent_id']   : -1; // subs of specific parent

        $where = ['1'];
        if ($activeOnly)    $where[] = 'is_active = 1';
        if ($parentOnly)    $where[] = '(parent_id IS NULL OR parent_id = 0)';
        if ($parentId >= 0) $where[] = 'parent_id = ' . $parentId;

        $sql = "SELECT id, account_code, account_name, account_type, parent_id, is_active
                FROM account_heads
                WHERE " . implode(' AND ', $where) . "
                ORDER BY account_type, account_name";
        $res = $mysqli->query($sql);
        $data = [];
        while ($row = $res->fetch_assoc()) $data[] = $row;
        json_response(['data' => $data]);
        break;

    case 'list_with_subs':
        // Returns parents with nested subs array — for the manage modal
        $activeOnly = isset($_GET['active_only']) ? (int)$_GET['active_only'] : 0;
        $where = $activeOnly ? 'WHERE is_active=1' : '';
        $res = $mysqli->query("SELECT id, account_code, account_name, account_type, parent_id, is_active
                               FROM account_heads $where ORDER BY account_type, account_name");
        $all = []; while ($row=$res->fetch_assoc()) $all[$row['id']] = $row;
        $parents = []; $subs = [];
        foreach ($all as $row) {
            if (!$row['parent_id']) $parents[] = $row;
            else $subs[(int)$row['parent_id']][] = $row;
        }
        foreach ($parents as &$p) $p['subs'] = $subs[$p['id']] ?? [];
        json_response(['data' => $parents]);
        break;

    case 'create':
        if (!has_role(['admin', 'super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $name     = trim($_POST['name'] ?? '');
        $type     = trim($_POST['category'] ?? 'Expense');
        $code     = trim($_POST['account_code'] ?? '') ?: null; // NULL if empty to avoid unique key conflict
        $parentId = (int)($_POST['parent_id'] ?? 0);
        if ($name === '') json_response(['message' => 'Name is required'], 400);
        if (!in_array($type, $validTypes)) json_response(['message' => 'Invalid account type'], 400);
        // If sub, inherit parent type
        if ($parentId > 0) {
            $pr = $mysqli->query("SELECT account_type FROM account_heads WHERE id=$parentId")->fetch_assoc();
            if ($pr) $type = $pr['account_type'];
        }
        $pId = $parentId ?: null;
        $stmt = $mysqli->prepare("INSERT INTO account_heads (account_code, account_name, account_type, parent_id) VALUES (?, ?, ?, ?)");
        $stmt->bind_param('sssi', $code, $name, $type, $pId);
        if (!$stmt->execute()) json_response(['message' => 'Duplicate or DB error: ' . $stmt->error], 500);
        json_response(['success' => true, 'id' => $mysqli->insert_id, 'message' => $parentId ? 'Sub account head created' : 'Account head created']);
        break;

    case 'update':
        if (!has_role(['admin', 'super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $id     = (int)($_POST['id'] ?? 0);
        $name   = trim($_POST['name'] ?? '');
        $type   = trim($_POST['category'] ?? '');
        $active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
        if (!$id || $name === '') json_response(['message' => 'ID and name required'], 400);
        if (!in_array($type, $validTypes)) json_response(['message' => 'Invalid account type'], 400);
        $stmt = $mysqli->prepare("UPDATE account_heads SET account_name=?, account_type=?, is_active=? WHERE id=?");
        $stmt->bind_param('ssii', $name, $type, $active, $id);
        if (!$stmt->execute()) json_response(['message' => 'Update failed: ' . $stmt->error], 500);
        // Also cascade type to subs
        $mysqli->query("UPDATE account_heads SET account_type='$type' WHERE parent_id=$id");
        json_response(['success' => true, 'message' => 'Updated']);
        break;

    case 'delete':
        if (!has_role(['admin', 'super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) json_response(['message' => 'ID required'], 400);
        // Delete subs first, then parent
        $mysqli->query("DELETE FROM account_heads WHERE parent_id=$id");
        $stmt = $mysqli->prepare("DELETE FROM account_heads WHERE id=?");
        $stmt->bind_param('i', $id);
        if (!$stmt->execute()) json_response(['message' => 'Delete failed'], 500);
        json_response(['success' => true, 'message' => 'Deleted']);
        break;

    default:
        json_response(['message' => 'Unknown action'], 400);
}
