<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success_message = '';

// Process account creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_account'])) {
    $account_code = trim($_POST['account_code'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    $account_type = $_POST['account_type'] ?? '';
    $account_category = trim($_POST['account_category'] ?? '');
    $parent_account_id = $_POST['parent_account_id'] ?? null;
    $normal_balance = $_POST['normal_balance'] ?? '';
    $description = trim($_POST['description'] ?? '');
    $is_header = isset($_POST['is_header']) ? 1 : 0;
    
    // Validation
    if (empty($account_code)) {
        $errors[] = "Account code is required";
    }
    
    if (empty($account_name)) {
        $errors[] = "Account name is required";
    }
    
    if (empty($account_type)) {
        $errors[] = "Account type is required";
    }
    
    if (empty($account_category)) {
        $errors[] = "Account category is required";
    }
    
    if (empty($normal_balance)) {
        $errors[] = "Normal balance is required";
    }
    
    // Check for duplicate account code
    if (empty($errors)) {
        $check_code_sql = "SELECT account_id FROM chart_of_accounts WHERE account_code = ?";
        $stmt = $conn->prepare($check_code_sql);
        $stmt->bind_param("s", $account_code);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "An account with this code already exists";
        }
    }
    
    // If no errors, create the account
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            $insert_sql = "INSERT INTO chart_of_accounts (
                          account_code, account_name, account_type, account_category,
                          parent_account_id, is_header, normal_balance, description,
                          current_balance, is_active, created_at
                          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0.00, 1, NOW())";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("ssssisss",
                $account_code, $account_name, $account_type, $account_category,
                $parent_account_id, $is_header, $normal_balance, $description
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create account: " . $stmt->error);
            }
            
            $new_account_id = $conn->insert_id;
            
            // Log the activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                           new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'ACCOUNTING', ?, 'ACCOUNT', ?, ?, NOW())";
            
            $activity_values = json_encode([
                'account_code' => $account_code,
                'account_name' => $account_name,
                'account_type' => $account_type,
                'normal_balance' => $normal_balance
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $new_account_id, $activity_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Account created successfully!<br>
                              <strong>Account Code:</strong> " . htmlspecialchars($account_code) . "<br>
                              <strong>Account Name:</strong> " . htmlspecialchars($account_name);
            
            // Clear form
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Failed to create account: " . $e->getMessage();
        }
    }
}

// Fetch all accounts organized by type
$accounts_sql = "SELECT * FROM chart_of_accounts 
                 WHERE is_active = 1 
                 ORDER BY account_code";
$accounts_result = $conn->query($accounts_sql);

$accounts_by_type = [
    'ASSET' => [],
    'LIABILITY' => [],
    'EQUITY' => [],
    'REVENUE' => [],
    'EXPENSE' => []
];

while ($account = $accounts_result->fetch_assoc()) {
    $accounts_by_type[$account['account_type']][] = $account;
}

// Get account summary
$summary_sql = "SELECT 
                    account_type,
                    COUNT(*) as account_count,
                    SUM(ABS(current_balance)) as total_balance
                FROM chart_of_accounts
                WHERE is_active = 1 AND is_header = 0
                GROUP BY account_type";
$summary_result = $conn->query($summary_sql);
$summary_data = [];
while ($row = $summary_result->fetch_assoc()) {
    $summary_data[$row['account_type']] = $row;
}

// Fetch parent accounts for dropdown
$parent_accounts_sql = "SELECT account_id, account_code, account_name, account_type 
                        FROM chart_of_accounts 
                        WHERE is_active = 1 
                        ORDER BY account_code";
$parent_accounts = $conn->query($parent_accounts_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Chart of Accounts')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .account-type-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .account-type-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .account-row {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background 0.2s;
        }
        
        .account-row:hover {
            background: #f8fafc;
        }
        
        .account-row:last-child {
            border-bottom: none;
        }
        
        .account-header-row {
            background: #f8fafc;
            font-weight: 600;
            padding-left: 2rem;
        }
        
        .account-code {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            color: #475569;
            min-width: 100px;
        }
        
        .account-name {
            flex: 1;
            font-weight: 500;
            color: #1e293b;
        }
        
        .account-balance {
            font-weight: 600;
            min-width: 150px;
            text-align: right;
        }
        
        .balance-debit {
            color: #059669;
        }
        
        .balance-credit {
            color: #dc2626;
        }
        
        .summary-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .required {
            color: #ef4444;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Chart of Accounts</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Chart of Accounts</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong><i class="ri-error-warning-line me-2"></i>Error!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong><i class="ri-checkbox-circle-line me-2"></i>Success!</strong>
                        <div class="mt-2"><?php echo $success_message; ?></div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Summary Box -->
                    <div class="summary-box">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="ri-bar-chart-line me-2"></i>Accounts Summary</h5>
                            <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#createAccountModal">
                                <i class="ri-add-line me-1"></i>Create New Account
                            </button>
                        </div>
                        <div class="row">
                            <div class="col-md-2">
                                <div class="summary-item">
                                    <span>Assets:</span>
                                    <strong><?php echo $summary_data['ASSET']['account_count'] ?? 0; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="summary-item">
                                    <span>Liabilities:</span>
                                    <strong><?php echo $summary_data['LIABILITY']['account_count'] ?? 0; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="summary-item">
                                    <span>Equity:</span>
                                    <strong><?php echo $summary_data['EQUITY']['account_count'] ?? 0; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-item">
                                    <span>Revenue:</span>
                                    <strong><?php echo $summary_data['REVENUE']['account_count'] ?? 0; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-item">
                                    <span>Expenses:</span>
                                    <strong><?php echo $summary_data['EXPENSE']['account_count'] ?? 0; ?></strong>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Account Types -->
                    <?php foreach ($accounts_by_type as $type => $accounts): ?>
                    <div class="account-type-card">
                        <div class="account-type-header">
                            <h5 class="mb-0">
                                <i class="ri-folder-line me-2"></i><?php echo $type; ?>
                            </h5>
                            <span class="badge bg-light text-dark">
                                <?php echo count($accounts); ?> accounts
                            </span>
                        </div>
                        <div class="account-type-body">
                            <?php foreach ($accounts as $account): ?>
                            <div class="account-row <?php echo $account['is_header'] ? 'account-header-row' : ''; ?>">
                                <span class="account-code"><?php echo htmlspecialchars($account['account_code']); ?></span>
                                <span class="account-name"><?php echo htmlspecialchars($account['account_name']); ?></span>
                                <?php if (!$account['is_header']): ?>
                                <span class="account-balance <?php echo $account['normal_balance'] === 'DEBIT' ? 'balance-debit' : 'balance-credit'; ?>">
                                    KES <?php echo number_format($account['current_balance'], 2); ?>
                                </span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Create Account Modal -->
    <div class="modal fade" id="createAccountModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="ri-add-circle-line me-2"></i>Create New Account</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Code <span class="required">*</span></label>
                                <input type="text" class="form-control" name="account_code" 
                                       placeholder="e.g., 1140" required>
                                <small class="text-muted">Unique code for this account</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Name <span class="required">*</span></label>
                                <input type="text" class="form-control" name="account_name" 
                                       placeholder="e.g., Prepaid Insurance" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Type <span class="required">*</span></label>
                                <select class="form-select" name="account_type" required>
                                    <option value="">Select Type</option>
                                    <option value="ASSET">ASSET</option>
                                    <option value="LIABILITY">LIABILITY</option>
                                    <option value="EQUITY">EQUITY</option>
                                    <option value="REVENUE">REVENUE</option>
                                    <option value="EXPENSE">EXPENSE</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Account Category <span class="required">*</span></label>
                                <input type="text" class="form-control" name="account_category" 
                                       placeholder="e.g., Current Assets" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Normal Balance <span class="required">*</span></label>
                                <select class="form-select" name="normal_balance" required>
                                    <option value="">Select Balance Type</option>
                                    <option value="DEBIT">DEBIT</option>
                                    <option value="CREDIT">CREDIT</option>
                                </select>
                                <small class="text-muted">Assets & Expenses: Debit | Liabilities, Equity & Revenue: Credit</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Parent Account</label>
                                <select class="form-select" name="parent_account_id">
                                    <option value="">No Parent (Top Level)</option>
                                    <?php 
                                    $parent_accounts->data_seek(0);
                                    while ($parent = $parent_accounts->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $parent['account_id']; ?>">
                                            <?php echo htmlspecialchars($parent['account_code'] . ' - ' . $parent['account_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12 mb-3">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="2" 
                                          placeholder="Optional description of this account"></textarea>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_header" id="isHeader">
                                    <label class="form-check-label" for="isHeader">
                                        This is a header/parent account (no transactions will be posted directly to this account)
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="ri-close-line me-1"></i>Cancel
                        </button>
                        <button type="submit" name="create_account" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i>Create Account
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
</body>
</html>