<?php
require_once 'config.php';
require_once 'db.php';

function getWebsiteContent($section = null) {
    global $pdo;
    
    if ($section) {
        $stmt = $pdo->prepare("SELECT * FROM website_content WHERE section = ?");
        $stmt->execute([$section]);
        return $stmt->fetch();
    } else {
        $content = [];
        $result = $pdo->query("SELECT * FROM website_content");
        while ($row = $result->fetch()) {
            $content[$row['section']] = $row;
        }
        return $content;
    }
}

function updateWebsiteContent($section, $title, $content, $imageUrl) {
    global $pdo;
    
    $stmt = $pdo->prepare("SELECT id FROM website_content WHERE section = ?");
    $stmt->execute([$section]);
    
    if ($stmt->fetch()) {
        // Update existing
        $stmt = $pdo->prepare("UPDATE website_content SET title = ?, content = ?, image_url = ? WHERE section = ?");
        return $stmt->execute([$title, $content, $imageUrl, $section]);
    } else {
        // Insert new
        $stmt = $pdo->prepare("INSERT INTO website_content (section, title, content, image_url) VALUES (?, ?, ?, ?)");
        return $stmt->execute([$section, $title, $content, $imageUrl]);
    }
}

function getAllGalleryImages() {
    global $pdo;
    return $pdo->query("SELECT * FROM gallery_images ORDER BY uploaded_at DESC")->fetchAll();
}

function uploadImage($file, $caption = '') {
    $targetDir = "../assets/images/";
    $fileName = uniqid() . '-' . basename($file["name"]);
    $targetFile = $targetDir . $fileName;
    
    // Check if image file is a actual image
    $check = getimagesize($file["tmp_name"]);
    if ($check === false) {
        return ['success' => false, 'message' => 'File is not an image'];
    }
    
    // Check file size (5MB max)
    if ($file["size"] > 5000000) {
        return ['success' => false, 'message' => 'File is too large (max 5MB)'];
    }
    
    // Allow certain file formats
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    if (!in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
        return ['success' => false, 'message' => 'Only JPG, JPEG, PNG & GIF files are allowed'];
    }
    
    // Upload file
    if (move_uploaded_file($file["tmp_name"], $targetFile)) {
        global $pdo;
        $stmt = $pdo->prepare("INSERT INTO gallery_images (image_url, caption) VALUES (?, ?)");
        $stmt->execute(["assets/images/" . $fileName, $caption]);
        return ['success' => true, 'file' => "assets/images/" . $fileName];
    } else {
        return ['success' => false, 'message' => 'Error uploading file'];
    }
}

function deleteImage($id) {
    global $pdo;
    
    // Get image URL first
    $stmt = $pdo->prepare("SELECT image_url FROM gallery_images WHERE id = ?");
    $stmt->execute([$id]);
    $image = $stmt->fetch();
    
    if ($image) {
        // Delete from filesystem
        $filePath = "../" . $image['image_url'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        
        // Delete from database
        $stmt = $pdo->prepare("DELETE FROM gallery_images WHERE id = ?");
        return $stmt->execute([$id]);
    }
    
    return false;
}
// Add these functions to your existing functions.php

// Service Functions
function getAllServices() {
    global $pdo;
    return $pdo->query("SELECT * FROM services ORDER BY created_at DESC")->fetchAll();
}

function getService($id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}

function saveService($data, $id = null) {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        if ($id) {
            // Update existing service
            $stmt = $pdo->prepare("UPDATE services SET title = ?, description = ?, icon = ?, image_url = ? WHERE id = ?");
            $stmt->execute([$data['title'], $data['description'], $data['icon'], $data['image_url'], $id]);
            
            // Delete existing features
            $pdo->prepare("DELETE FROM service_features WHERE service_id = ?")->execute([$id]);
        } else {
            // Create new service
            $stmt = $pdo->prepare("INSERT INTO services (title, description, icon, image_url) VALUES (?, ?, ?, ?)");
            $stmt->execute([$data['title'], $data['description'], $data['icon'], $data['image_url']]);
            $id = $pdo->lastInsertId();
        }
        
        // Save features
        if (!empty($data['features'])) {
            $featureStmt = $pdo->prepare("INSERT INTO service_features (service_id, feature_text, sort_order) VALUES (?, ?, ?)");
            foreach ($data['features'] as $index => $feature) {
                if (!empty(trim($feature))) {
                    $featureStmt->execute([$id, trim($feature), $index]);
                }
            }
        }
        
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Error saving service: " . $e->getMessage());
        return false;
    }
}

function deleteService($id) {
    global $pdo;
    $stmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
    return $stmt->execute([$id]);
}

// Project Functions
function getAllProjects() {
    global $pdo;
    return $pdo->query("SELECT * FROM projects ORDER BY completed_date DESC")->fetchAll();
}

function getProject($id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}

function saveProject($data, $id = null) {
    global $pdo;
    
    if ($id) {
        // Update existing project
        $stmt = $pdo->prepare("UPDATE projects SET title = ?, description = ?, image_url = ?, client = ?, location = ?, completed_date = ? WHERE id = ?");
        return $stmt->execute([
            $data['title'], 
            $data['description'], 
            $data['image_url'],
            $data['client'],
            $data['location'],
            $data['completed_date'],
            $id
        ]);
    } else {
        // Create new project
        $stmt = $pdo->prepare("INSERT INTO projects (title, description, image_url, client, location, completed_date) VALUES (?, ?, ?, ?, ?, ?)");
        return $stmt->execute([
            $data['title'], 
            $data['description'], 
            $data['image_url'],
            $data['client'],
            $data['location'],
            $data['completed_date']
        ]);
    }
}

function deleteProject($id) {
    global $pdo;
    $stmt = $pdo->prepare("DELETE FROM projects WHERE id = ?");
    return $stmt->execute([$id]);
}
?>