<?php
session_start();
require_once __DIR__ . '/../config/db.php';

// Use $connection from config/db.php
$conn = $connection;

// Check admin authentication
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Create team table if it doesn't exist
$create_table_sql = "CREATE TABLE IF NOT EXISTS team_members (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    designation VARCHAR(100) NOT NULL,
    image_path VARCHAR(255),
    twitter_url VARCHAR(255),
    linkedin_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_created (created_at)
)";
$conn->query($create_table_sql);

// Initialize team members from team.html if table is empty
$count_result = $conn->query("SELECT COUNT(*) as count FROM team_members");
$count_row = $count_result->fetch_assoc();

if ($count_row['count'] == 0) {
    // Parse team.html to extract team members
    $team_html_file = __DIR__ . '/../team.html';
    if (file_exists($team_html_file)) {
        $html_content = file_get_contents($team_html_file);
        
        // Extract team members using regex pattern
        if (preg_match_all('/<div class="col-md-6 col-xl-4">.*?<img src="([^"]+)"[^>]*alt="Team".*?<a href="team-details.html">([^<]+)<\/a><\/h3><span\s+class="team-desig">([^<]+)<\/span>/s', $html_content, $matches)) {
            for ($i = 0; $i < count($matches[1]); $i++) {
                $image_path = $matches[1][$i];
                $name = $matches[2][$i];
                $designation = $matches[3][$i];
                $twitter_url = 'https://twitter.com/';
                $linkedin_url = 'https://linkedin.com/';
                
                $stmt = $conn->prepare("INSERT INTO team_members (name, designation, image_path, twitter_url, linkedin_url) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param('sssss', $name, $designation, $image_path, $twitter_url, $linkedin_url);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
}

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action === 'get_all') {
    // Get all team members
    $result = $conn->query("SELECT * FROM team_members ORDER BY created_at DESC");
    $team_members = [];
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $team_members[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $team_members]);
    
} elseif ($action === 'add') {
    // Add new team member
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $designation = isset($_POST['designation']) ? trim($_POST['designation']) : '';
    $twitter_url = isset($_POST['twitter_url']) ? trim($_POST['twitter_url']) : '';
    $linkedin_url = isset($_POST['linkedin_url']) ? trim($_POST['linkedin_url']) : '';
    
    $image_path = '';
    
    // Handle file upload
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['image'];
        $upload_dir = __DIR__ . '/../assets/img/team/';
        
        // Create directory if it doesn't exist
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Generate unique filename
        $filename = 'team_' . time() . '_' . rand(1000, 9999) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
        $filepath = $upload_dir . $filename;
        
        // Validate file type
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($file['type'], $allowed_types) && move_uploaded_file($file['tmp_name'], $filepath)) {
            $image_path = 'assets/img/team/' . $filename;
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid image file']);
            exit;
        }
    }
    
    if (empty($name) || empty($designation)) {
        echo json_encode(['success' => false, 'message' => 'Name and designation are required']);
        exit;
    }
    
    $stmt = $conn->prepare("INSERT INTO team_members (name, designation, image_path, twitter_url, linkedin_url) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param('sssss', $name, $designation, $image_path, $twitter_url, $linkedin_url);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Team member added successfully', 'id' => $stmt->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error adding team member: ' . $conn->error]);
    }
    $stmt->close();
    
} elseif ($action === 'edit') {
    // Edit team member
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $designation = isset($_POST['designation']) ? trim($_POST['designation']) : '';
    $twitter_url = isset($_POST['twitter_url']) ? trim($_POST['twitter_url']) : '';
    $linkedin_url = isset($_POST['linkedin_url']) ? trim($_POST['linkedin_url']) : '';
    
    if (empty($id) || empty($name) || empty($designation)) {
        echo json_encode(['success' => false, 'message' => 'Invalid data provided']);
        exit;
    }
    
    // Get current image path
    $result = $conn->query("SELECT image_path FROM team_members WHERE id = $id");
    $current = $result->fetch_assoc();
    $image_path = $current['image_path'];
    
    // Handle file upload if new image is provided
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['image'];
        $upload_dir = __DIR__ . '/../assets/img/team/';
        
        // Delete old image
        if (!empty($current['image_path']) && file_exists(__DIR__ . '/../' . $current['image_path'])) {
            unlink(__DIR__ . '/../' . $current['image_path']);
        }
        
        $filename = 'team_' . time() . '_' . rand(1000, 9999) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
        $filepath = $upload_dir . $filename;
        
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($file['type'], $allowed_types) && move_uploaded_file($file['tmp_name'], $filepath)) {
            $image_path = 'assets/img/team/' . $filename;
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid image file']);
            exit;
        }
    }
    
    $stmt = $conn->prepare("UPDATE team_members SET name = ?, designation = ?, image_path = ?, twitter_url = ?, linkedin_url = ? WHERE id = ?");
    $stmt->bind_param('sssssi', $name, $designation, $image_path, $twitter_url, $linkedin_url, $id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Team member updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating team member: ' . $conn->error]);
    }
    $stmt->close();
    
} elseif ($action === 'delete') {
    // Delete team member
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if (empty($id)) {
        echo json_encode(['success' => false, 'message' => 'Invalid ID']);
        exit;
    }
    
    // Get image path and delete it
    $result = $conn->query("SELECT image_path FROM team_members WHERE id = $id");
    $row = $result->fetch_assoc();
    
    if (!empty($row['image_path']) && file_exists(__DIR__ . '/../' . $row['image_path'])) {
        unlink(__DIR__ . '/../' . $row['image_path']);
    }
    
    $stmt = $conn->prepare("DELETE FROM team_members WHERE id = ?");
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Team member deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting team member: ' . $conn->error]);
    }
    $stmt->close();
    
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
