Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/newsfeed/classes/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/newsfeed/classes/Location.php

<?php
/**
 * Location Class - Manages church locations (Areas, Districts, Assemblies)
 */

class Location {
    private $pdo;
    private $lastError;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Create a new location
     */
    public function create($data) {
        try {
            $sql = "INSERT INTO locations (name, type, parent_id, address, contact_person, contact_phone, contact_email, description, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $this->pdo->prepare($sql);
            $result = $stmt->execute([
                $data['name'],
                $data['type'],
                $data['parent_id'] ?: null,
                $data['address'] ?: null,
                $data['contact_person'] ?: null,
                $data['contact_phone'] ?: null,
                $data['contact_email'] ?: null,
                $data['description'] ?: null,
                $data['created_by']
            ]);
            
            if ($result) {
                $locationId = $this->pdo->lastInsertId();
                
                // Log the action
                if (function_exists('logAudit')) {
                    logAudit($data['created_by'], 'location_created', "Created location: {$data['name']} ({$data['type']})");
                }
                
                return $locationId;
            }
            
            return false;
        } catch (PDOException $e) {
            error_log("Location creation error: " . $e->getMessage());
            // Also store the error message for debugging
            $this->lastError = $e->getMessage();
            return false;
        }
    }
    
    /**
     * Get the last error message
     */
    public function getLastError() {
        return $this->lastError ?? 'Unknown error';
    }
    
    /**
     * Get location by ID
     */
    public function getById($id) {
        try {
            $sql = "SELECT l.*, p.name as parent_name, u.name as created_by_name 
                    FROM locations l 
                    LEFT JOIN locations p ON l.parent_id = p.id 
                    LEFT JOIN users u ON l.created_by = u.id 
                    WHERE l.id = ?";
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute([$id]);
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Location fetch error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get all locations with optional filters
     */
    public function getAll($filters = []) {
        try {
            $sql = "SELECT l.*, p.name as parent_name, u.name as created_by_name 
                    FROM locations l 
                    LEFT JOIN locations p ON l.parent_id = p.id 
                    LEFT JOIN users u ON l.created_by = u.id 
                    WHERE 1=1";
            
            $params = [];
            
            if (!empty($filters['type'])) {
                $sql .= " AND l.type = ?";
                $params[] = $filters['type'];
            }
            
            if (!empty($filters['status'])) {
                $sql .= " AND l.status = ?";
                $params[] = $filters['status'];
            }
            
            if (!empty($filters['parent_id'])) {
                $sql .= " AND l.parent_id = ?";
                $params[] = $filters['parent_id'];
            }
            
            if (!empty($filters['search'])) {
                $sql .= " AND (l.name LIKE ? OR l.address LIKE ? OR l.contact_person LIKE ?)";
                $searchTerm = '%' . $filters['search'] . '%';
                $params[] = $searchTerm;
                $params[] = $searchTerm;
                $params[] = $searchTerm;
            }
            
            $sql .= " ORDER BY l.type, l.name";
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Locations fetch error: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Update location
     */
    public function update($id, $data) {
        try {
            $sql = "UPDATE locations SET 
                    name = ?, type = ?, parent_id = ?, address = ?, 
                    contact_person = ?, contact_phone = ?, contact_email = ?, 
                    description = ?, status = ?
                    WHERE id = ?";
            
            $stmt = $this->pdo->prepare($sql);
            $result = $stmt->execute([
                $data['name'],
                $data['type'],
                $data['parent_id'] ?: null,
                $data['address'] ?: null,
                $data['contact_person'] ?: null,
                $data['contact_phone'] ?: null,
                $data['contact_email'] ?: null,
                $data['description'] ?: null,
                $data['status'] ?: 'active',
                $id
            ]);
            
            if ($result && function_exists('logAudit')) {
                logAudit($_SESSION['user_id'], 'location_updated', "Updated location: {$data['name']} (ID: $id)");
            }
            
            return $result;
        } catch (PDOException $e) {
            error_log("Location update error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete location
     */
    public function delete($id) {
        try {
            // First check if location has children
            $childrenStmt = $this->pdo->prepare("SELECT COUNT(*) FROM locations WHERE parent_id = ?");
            $childrenStmt->execute([$id]);
            $childrenCount = $childrenStmt->fetchColumn();
            
            if ($childrenCount > 0) {
                return ['error' => 'Cannot delete location that has child locations'];
            }
            
            // Get location name for audit log
            $location = $this->getById($id);
            
            $stmt = $this->pdo->prepare("DELETE FROM locations WHERE id = ?");
            $result = $stmt->execute([$id]);
            
            if ($result && $location && function_exists('logAudit')) {
                logAudit($_SESSION['user_id'], 'location_deleted', "Deleted location: {$location['name']} (ID: $id)");
            }
            
            return $result;
        } catch (PDOException $e) {
            error_log("Location deletion error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get locations by type
     */
    public function getByType($type) {
        return $this->getAll(['type' => $type, 'status' => 'active']);
    }
    
    /**
     * Get child locations
     */
    public function getChildren($parentId) {
        return $this->getAll(['parent_id' => $parentId, 'status' => 'active']);
    }
    
    /**
     * Check if location name exists for a type
     */
    public function nameExists($name, $type, $excludeId = null) {
        try {
            $sql = "SELECT COUNT(*) FROM locations WHERE name = ? AND type = ?";
            $params = [$name, $type];
            
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            
            return $stmt->fetchColumn() > 0;
        } catch (PDOException $e) {
            error_log("Location name check error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get location statistics
     */
    public function getStats() {
        try {
            $stats = [];
            
            // Count by type
            $stmt = $this->pdo->prepare("SELECT type, COUNT(*) as count FROM locations WHERE status = 'active' GROUP BY type");
            $stmt->execute();
            $typeStats = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($typeStats as $stat) {
                $stats[$stat['type']] = $stat['count'];
            }
            
            // Total active locations
            $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM locations WHERE status = 'active'");
            $stmt->execute();
            $stats['total_active'] = $stmt->fetchColumn();
            
            // Total inactive locations
            $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM locations WHERE status = 'inactive'");
            $stmt->execute();
            $stats['total_inactive'] = $stmt->fetchColumn();
            
            return $stats;
        } catch (PDOException $e) {
            error_log("Location stats error: " . $e->getMessage());
            return [];
        }
    }
}
?>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists