cd /home/tanahtin/museum.pondoktingal.com

# =============================================
# 1. FIX COUNTRIES - Remove ID column
# =============================================

cat > admin/countries/index.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$db = getDB();
$countries = $db->query("SELECT * FROM countries ORDER BY name");

include dirname(__DIR__) . '/header.php';
?>

<div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 class="page-title">Countries</h1>
        <a href="create.php" class="btn btn-primary">+ Add New Country</a>
    </div>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">Country saved successfully!</div>
    <?php endif; ?>
    
    <div class="table-container">
        <table>
            <thead>
                <tr><th>Country Name</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php while($row = $countries->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($row['name']); ?></strong></td>
                    <td>
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this country? All districts will be deleted too.')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 2. FIX DISTRICTS - Remove ID column
# =============================================

cat > admin/districts/index.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$db = getDB();
$country_filter = isset($_GET['country_id']) ? intval($_GET['country_id']) : 0;

if ($country_filter) {
    $districts = $db->query("SELECT d.*, c.name as country_name FROM districts d 
                             JOIN countries c ON d.country_id = c.id 
                             WHERE d.country_id = $country_filter 
                             ORDER BY d.name");
} else {
    $districts = $db->query("SELECT d.*, c.name as country_name FROM districts d 
                             JOIN countries c ON d.country_id = c.id 
                             ORDER BY c.name, d.name");
}

$countries = getCountries();

include dirname(__DIR__) . '/header.php';
?>

<div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 class="page-title">Districts / Regions</h1>
        <a href="create.php" class="btn btn-primary">+ Add New District</a>
    </div>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">District saved successfully!</div>
    <?php endif; ?>
    
    <div class="filter-bar">
        <label>Filter by Country:</label>
        <select name="country_id" onchange="window.location.href='?country_id='+this.value">
            <option value="0">All Countries</option>
            <?php foreach($countries as $c): ?>
            <option value="<?php echo $c['id']; ?>" <?php echo $country_filter == $c['id'] ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($c['name']); ?>
            </option>
            <?php endforeach; ?>
        </select>
    </div>
    
    <div class="table-container">
        <table>
            <thead>
                <tr><th>Country</th><th>District</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php while($row = $districts->fetch_assoc()): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['country_name']); ?></td>
                    <td><strong><?php echo htmlspecialchars($row['name']); ?></strong></td>
                    <td>
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this district?')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 3. FIX CHARACTERS - Remove ID column
# =============================================

cat > admin/characters/index.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$db = getDB();
$characters = $db->query("SELECT * FROM characters ORDER BY name");

include dirname(__DIR__) . '/header.php';
?>

<div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 class="page-title">Characters</h1>
        <a href="create.php" class="btn btn-primary">+ Add New Character</a>
    </div>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">Character saved successfully!</div>
    <?php endif; ?>
    
    <div class="table-container">
        <table>
            <thead>
                <tr><th>Name</th><th>Type</th><th>Description</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php while($row = $characters->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($row['name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($row['type'] ?: '-'); ?></td>
                    <td><?php echo htmlspecialchars(substr($row['description'], 0, 100)); ?>...</td>
                    <td>
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this character?')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 4. FIX COLLECTIONS - Remove ID column
# =============================================

cat > admin/collections/index.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$db = getDB();
$collections = $db->query("SELECT c.*, co.name as country_name, d.name as district_name 
                           FROM collections c
                           LEFT JOIN countries co ON c.country_id = co.id
                           LEFT JOIN districts d ON c.district_id = d.id
                           ORDER BY c.crate_number");

include dirname(__DIR__) . '/header.php';
?>

<div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 class="page-title">Collections (Crates)</h1>
        <a href="create.php" class="btn btn-primary">+ Add New Crate</a>
    </div>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">Collection saved successfully!</div>
    <?php endif; ?>
    
    <div class="table-container">
        <table>
            <thead>
                <tr><th>Crate #</th><th>Name</th><th>Country</th><th>District</th><th>Puppets</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php while($row = $collections->fetch_assoc()): ?>
                <tr>
                    <td><strong>#<?php echo $row['crate_number']; ?></strong></td>
                    <td><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo htmlspecialchars($row['country_name'] ?: '-'); ?></td>
                    <td><?php echo htmlspecialchars($row['district_name'] ?: '-'); ?></td>
                    <td><?php echo $row['total_puppets']; ?></td>
                    <td>
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                        <a href="/admin/images/?collection_id=<?php echo $row['id']; ?>" class="btn btn-warning btn-sm">View Images</a>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this crate and all its images?')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 5. FIX USERS - Remove ID column (if exists)
# =============================================

cat > admin/users/index.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

requireAdmin();

$db = getDB();
$users = $db->query("SELECT id, username, full_name, role, is_active, created_at, last_login FROM users ORDER BY id");

include dirname(__DIR__) . '/header.php';
?>

<div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 class="page-title">Manage Users</h1>
        <a href="create.php" class="btn btn-primary">+ Add New User</a>
    </div>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">User saved successfully!</div>
    <?php endif; ?>
    <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-success">User deleted successfully!</div>
    <?php endif; ?>
    
    <div class="table-container">
        <table>
            <thead>
                <tr><th>Username</th><th>Full Name</th><th>Role</th><th>Status</th><th>Created</th><th>Last Login</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php while($row = $users->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($row['username']); ?></strong></td>
                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                    <td><?php echo $row['role'] == 'admin' ? '👑 Admin' : '✏️ Editor'; ?></td>
                    <td><?php echo $row['is_active'] ? '<span style="color: #10b981;">✓ Active</span>' : '<span style="color: #ef4444;">✗ Disabled</span>'; ?></td>
                    <td><?php echo $row['created_at']; ?></td>
                    <td><?php echo $row['last_login'] ?: 'Never'; ?></td>
                    <td>
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                        <?php if($row['username'] != 'admin'): ?>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this user?')">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 6. FIX COLLECTIONS CREATE - District dropdown AJAX
# =============================================

cat > admin/collections/create.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$error = '';
$countries = getCountries();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $crate_number = intval($_POST['crate_number']);
    $country_id = intval($_POST['country_id']);
    $district_id = !empty($_POST['district_id']) ? intval($_POST['district_id']) : null;
    $description = trim($_POST['description']);
    $total_puppets = intval($_POST['total_puppets']);
    
    if (empty($name) || $crate_number <= 0 || $country_id <= 0) {
        $error = 'Name, Crate Number, and Country are required';
    } else {
        $db = getDB();
        $stmt = $db->prepare("INSERT INTO collections (name, crate_number, country_id, district_id, description, total_puppets) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("siissi", $name, $crate_number, $country_id, $district_id, $description, $total_puppets);
        
        if ($stmt->execute()) {
            header('Location: index.php?success=1');
            exit();
        } else {
            $error = 'Error: ' . $db->error;
        }
    }
}

include dirname(__DIR__) . '/header.php';
?>

<div class="form-card">
    <h1 class="page-title" style="margin-top: 0;">Add New Collection Crate</h1>
    
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <form method="POST" id="collectionForm">
        <div class="form-group">
            <label>Crate Name *</label>
            <input type="text" name="name" placeholder="e.g., Wayang Kedu" required>
        </div>
        <div class="form-group">
            <label>Crate Number * (1-15)</label>
            <input type="number" name="crate_number" min="1" max="15" required>
        </div>
        <div class="form-group">
            <label>Country *</label>
            <select name="country_id" id="country_id" required>
                <option value="">Select Country</option>
                <?php foreach($countries as $c): ?>
                <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>District (Optional)</label>
            <select name="district_id" id="district_id">
                <option value="">-- Select Country First --</option>
            </select>
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="4" placeholder="Describe this collection..."></textarea>
        </div>
        <div class="form-group">
            <label>Total Puppets in Crate</label>
            <input type="number" name="total_puppets" min="0" value="0">
        </div>
        <div style="display: flex; gap: 12px;">
            <button type="submit" class="btn btn-primary">Save Collection</button>
            <a href="index.php" class="btn btn-warning">Cancel</a>
        </div>
    </form>
</div>

<script>
document.getElementById('country_id').addEventListener('change', function() {
    var countryId = this.value;
    var districtSelect = document.getElementById('district_id');
    
    if (countryId) {
        districtSelect.innerHTML = '<option value="">Loading districts...</option>';
        fetch('../../includes/ajax_districts.php?country_id=' + countryId)
            .then(response => response.json())
            .then(data => {
                districtSelect.innerHTML = '<option value="">-- Select District (Optional) --</option>';
                if (data.length === 0) {
                    districtSelect.innerHTML += '<option value="" disabled>No districts available</option>';
                } else {
                    data.forEach(district => {
                        districtSelect.innerHTML += '<option value="' + district.id + '">' + district.name + '</option>';
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                districtSelect.innerHTML = '<option value="">Error loading districts</option>';
            });
    } else {
        districtSelect.innerHTML = '<option value="">-- Select Country First --</option>';
    }
});
</script>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 7. FIX COLLECTIONS EDIT - District dropdown
# =============================================

cat > admin/collections/edit.php << 'EOF'
<?php
require_once dirname(__DIR__) . '/session_check.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $crate_number = intval($_POST['crate_number']);
    $country_id = intval($_POST['country_id']);
    $district_id = !empty($_POST['district_id']) ? intval($_POST['district_id']) : null;
    $description = trim($_POST['description']);
    $total_puppets = intval($_POST['total_puppets']);
    
    $stmt = $db->prepare("UPDATE collections SET name = ?, crate_number = ?, country_id = ?, district_id = ?, description = ?, total_puppets = ? WHERE id = ?");
    $stmt->bind_param("siiissi", $name, $crate_number, $country_id, $district_id, $description, $total_puppets, $id);
    
    if ($stmt->execute()) {
        header('Location: index.php?success=1');
        exit();
    }
}

$result = $db->query("SELECT * FROM collections WHERE id = $id");
$collection = $result->fetch_assoc();

if (!$collection) {
    header('Location: index.php');
    exit();
}

$countries = getCountries();
$current_districts = getDistricts($collection['country_id']);

include dirname(__DIR__) . '/header.php';
?>

<div class="form-card">
    <h1 class="page-title" style="margin-top: 0;">Edit Collection Crate</h1>
    
    <form method="POST" id="collectionForm">
        <div class="form-group">
            <label>Crate Name</label>
            <input type="text" name="name" value="<?php echo htmlspecialchars($collection['name']); ?>" required>
        </div>
        <div class="form-group">
            <label>Crate Number</label>
            <input type="number" name="crate_number" value="<?php echo $collection['crate_number']; ?>" min="1" max="15" required>
        </div>
        <div class="form-group">
            <label>Country</label>
            <select name="country_id" id="country_id" required>
                <?php foreach($countries as $c): ?>
                <option value="<?php echo $c['id']; ?>" <?php echo $collection['country_id'] == $c['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($c['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>District</label>
            <select name="district_id" id="district_id">
                <option value="">None</option>
                <?php foreach($current_districts as $d): ?>
                <option value="<?php echo $d['id']; ?>" <?php echo $collection['district_id'] == $d['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($d['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="4"><?php echo htmlspecialchars($collection['description']); ?></textarea>
        </div>
        <div class="form-group">
            <label>Total Puppets</label>
            <input type="number" name="total_puppets" value="<?php echo $collection['total_puppets']; ?>" min="0">
        </div>
        <div style="display: flex; gap: 12px;">
            <button type="submit" class="btn btn-primary">Update Collection</button>
            <a href="index.php" class="btn btn-warning">Cancel</a>
        </div>
    </form>
</div>

<script>
document.getElementById('country_id').addEventListener('change', function() {
    var countryId = this.value;
    var districtSelect = document.getElementById('district_id');
    var currentDistrict = <?php echo json_encode($collection['district_id']); ?>;
    
    if (countryId) {
        districtSelect.innerHTML = '<option value="">Loading districts...</option>';
        fetch('../../includes/ajax_districts.php?country_id=' + countryId)
            .then(response => response.json())
            .then(data => {
                districtSelect.innerHTML = '<option value="">None</option>';
                data.forEach(district => {
                    var selected = (district.id == currentDistrict) ? 'selected' : '';
                    districtSelect.innerHTML += '<option value="' + district.id + '" ' + selected + '>' + district.name + '</option>';
                });
            })
            .catch(error => {
                console.error('Error:', error);
                districtSelect.innerHTML = '<option value="">Error loading districts</option>';
            });
    }
});
</script>

<?php include dirname(__DIR__) . '/footer.php'; ?>
EOF

# =============================================
# 8. VERIFY AJAX FILE EXISTS
# =============================================

cat > includes/ajax_districts.php << 'EOF'
<?php
require_once 'config.php';
require_once 'functions.php';

header('Content-Type: application/json');

$country_id = isset($_GET['country_id']) ? intval($_GET['country_id']) : 0;

if ($country_id > 0) {
    $db = getDB();
    $result = $db->query("SELECT id, name FROM districts WHERE country_id = $country_id ORDER BY name");
    $districts = $result->fetch_all(MYSQLI_ASSOC);
} else {
    $districts = [];
}

echo json_encode($districts);
?>
EOF

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}FIXES COMPLETE!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "\n${YELLOW}Changes made:${NC}"
echo -e "  ✓ Removed ID column from all table views"
echo -e "  ✓ Fixed district dropdown to update when country changes"
echo -e "\n${YELLOW}Refresh your browser (Ctrl+Shift+R)${NC}"