<?php 
require_once './includes/nav.php'; 

if($_POST) {
	// Vérifier le token CSRF
	if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
		echo "<div class='alert alert-error'>Token de sécurité invalide.</div>";
	} else {
		// Handle form submission for project creation
		if(isset($_POST['name']) && isset($_POST['description']) && isset($_POST['start_date'])) {
			$type = sanitizeInput($_POST['type']);
			$name = sanitizeInput($_POST['name']);
			$description = sanitizeInput($_POST['description']);
			$start_date = sanitizeInput($_POST['start_date']);
			$end_date = isset($_POST['end_date']) && !empty($_POST['end_date']) ? sanitizeInput($_POST['end_date']) : null;
			$link = isset($_POST['link']) && !empty($_POST['link']) ? sanitizeInput($_POST['link']) : null;
			$technologies = isset($_POST['technologies']) && !empty($_POST['technologies']) ? 
				array_map('trim', explode(',', sanitizeInput($_POST['technologies']))) : [];
			$tags = isset($_POST['tags']) && !empty($_POST['tags']) ? 
				array_map('trim', explode(',', sanitizeInput($_POST['tags']))) : [];

			// Validation des données
			if (empty($type) || empty($name) || empty($description) || empty($start_date)) {
				echo "<div class='alert alert-error'>Tous les champs obligatoires doivent être remplis.</div>";
			} elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
				echo "<div class='alert alert-error'>Format de date de début invalide.</div>";
			} elseif ($end_date && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
				echo "<div class='alert alert-error'>Format de date de fin invalide.</div>";
			} else {
				$jsonFile = '../data/projects.json';
				// Read existing projects
				if(file_exists($jsonFile)) {
					$content = file_get_contents($jsonFile);
					$projects = $content ? json_decode($content, true) : [];
				} else {
					$projects = [];
				}

				// Create new project entry
				$newProject = [
					'id' => uniqid(),
					'type' => $type,
					'name' => $name,
					'description' => $description,
					'link' => $link,
					'technologies' => $technologies,
					'start_date' => $start_date,
					'end_date' => $end_date,
					'created_at' => date('Y-m-d H:i:s'),
					'active' => true
				];

				// Add new project to the list
				$projects[] = $newProject;

				// Save updated projects back to the JSON file
				if (file_put_contents($jsonFile, json_encode($projects, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
					echo "<div class='alert alert-success'>Projet '$name' créé avec succès !</div>";
					// Reset form fields
					unset($_POST);
				} else {
					echo "<div class='alert alert-error'>Erreur lors de la sauvegarde du projet.</div>";
				}
			}
		}
	}
}
?>
<section>
	<div class="dashboard" data-type="projects">
		<div class="projects-actions">
			<h1>Projets</h1>
			<a href="#" class="btn-success" data-id="creation-project-btn">Ajouter projet</a>
		</div>
	<div class="form-project hidden">
		<form action="" method="post">
			<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(generateCSRFToken()); ?>">
			<div class="form-group">
				<label for="project-type">Type du projet *</label>
				<input type="text" id="project-type" name="type" placeholder="Ex: Site vitrine e-commerce" required maxlength="100">
			</div>
			<div class="form-group">
				<label for="project-name">Nom du projet *</label>
				<input type="text" id="project-name" name="name" placeholder="Ex: Sandwicherie" required maxlength="150">
			</div>
			<div class="form-group">
				<label for="project-description">Description *</label>
				<textarea id="project-description" name="description" placeholder="Décrivez votre projet, les technologies utilisées, les défis relevés..." required maxlength="1000"></textarea>
			</div>
			<div class="form-group">
				<label for="project-image">Lien du projet</label>
				<input type="url" id="project-link" name="link" placeholder="https://exemple.com/projet" maxlength="255">
			</div>
			<div class="form-group">
				<label for="project-technologies">Technologies utilisées *</label>
				<div class="technologies-grid">
					<!-- Le contenu sera généré par JavaScript -->
					<div class="loading-technologies">
						<p>Chargement des technologies...</p>
					</div>
				</div>
				<input type="hidden" id="selected-technologies" name="technologies">
			</div>
			<div class="form-group">
				<label for="project-tags">Tags (séparés par des virgules)</label>
				<input type="text" id="project-tags" name="tags" placeholder="Ex: responsive, moderne, e-commerce" maxlength="200">
				<small class="form-help">Ajoutez des mots-clés pour décrire votre projet (séparés par des virgules)</small>
			</div>
			<div class="form-group">
				<label for="project-start-date">Date de début *</label>
				<input type="date" id="project-start-date" name="start_date" required>
			</div>
			<div class="form-group">
				<label for="project-end-date">Date de fin</label>
				<input type="date" id="project-end-date" name="end_date">
			</div>
				<button type="submit" class="btn-success">Enregistrer</button>
			</form>
		</div>
		<div data-id="projects">
			<div class="projects-grid"></div>
		</div>
	</div>
</section>

<script src="../Static/js/technologies.js"></script>