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

// Check login
if (!isset($_SESSION['user_id'])) {
	header("Location: ../../auth/login.php");
	exit;
}

$username = $_SESSION['username'];
$role = $_SESSION['role'];
$user_id = $_SESSION['user_id'];

// Restrict to admin only
if ($role !== 'admin') {
	header("Location: ../dashboard.php");
	exit;
}

// CSRF token
if (!isset($_SESSION['csrf_token'])) {
	$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$message = '';
$project = null;

// Get project ID from query
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
	header("Location: ../projects/");
	exit;
}

$project_id = (int)$_GET['id'];

// Fetch project
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
$stmt->execute([$project_id]);
$project = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$project) {
	$message = "Project not found.";
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $project) {
	if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
		$message = "Invalid CSRF token.";
	} else {
		$name = trim($_POST['name']);
		$code = trim($_POST['code']);
		$description = trim($_POST['description']);
		$status = $_POST['status'];

		if ($name === '' || $code === '' || $description === '') {
			$message = "Please fill in all fields.";
		} else {
			$stmt = $pdo->prepare("UPDATE projects SET name = ?, code = ?, description = ?, status = ?, updated_by = ?, updated_at = NOW() WHERE id = ?");
			try {
				$stmt->execute([$name, $code, $description, $status, $user_id, $project_id]);
				$message = "✅ Project updated successfully!";
				
				// Optional: Send notification
				$subject = "Project Updated: {$name}";
				$body = "<p>Project <b>{$name}</b> (Code: {$code}) has been updated by {$username} (Admin).</p>";
				send_email('systems@digivortlimited.com', 'Systems Team', $subject, $body);

				// Refresh project data
				$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
				$stmt->execute([$project_id]);
				$project = $stmt->fetch(PDO::FETCH_ASSOC);

			} catch (PDOException $e) {
				if ($e->getCode() == 23000) {
					$message = "⚠️ Project code already exists.";
				} else {
					$message = "❌ Failed to update project: " . $e->getMessage();
				}
			}
		}
	}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Project - Custora CRM</title>
<link rel="icon" href="../assets/img/custora_logo.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
/* Reuse your previous CSS here */
/* Keep all the sidebar, dark mode, form, etc. styles */
:root{--bg:#f4f7fa;--card-bg:rgba(173,216,230,0.35);--accent:#005f8d;--muted:#555;--text:#1b2430;--white:#fff;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Inter,"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--text);}
a{text-decoration:none;color:inherit;}
.app{display:flex;min-height:100vh;}
.sidebar{width:250px;background:skyblue;color:#003547;position:fixed;left:0;top:0;height:100vh;overflow:auto;z-index:200;transition:transform .3s ease-in-out;}
.sidebar .logo{text-align:center;margin:15px 0;}
.sidebar .logo img{width:180px;height:auto;margin-top:20px;}
.nav{margin-top:12px;padding-left:10px;}
.nav a{display:block;padding:10px 14px;color:#003547;border-radius:8px;margin-bottom:6px;font-weight:600;}
.nav a:hover{background:rgba(255,255,255,0.8);box-shadow:0 2px 6px rgba(0,0,0,0.06);}
.footer-note{text-align:center;font-size:13px;padding:10px;color:var(--muted);}
.main{margin-left:260px;padding:20px;width:100%;transition:margin-left .25s;}
.header{background:var(--accent);color:white;padding:15px 20px;border-radius:8px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;}
.header-left{display:flex;align-items:center;gap:10px;}
.hamburger{display:none;background:var(--accent);color:white;padding:8px 10px;border-radius:8px;cursor:pointer;font-size:20px;}
.overlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.4);z-index:150;}
.content{background:var(--card-bg);padding:25px;border-radius:12px;box-shadow:0 4px 10px rgba(0,0,0,0.08);}
.content h3{color:var(--accent);margin-bottom:15px;}
.message{background:#d4edda;color:#155724;padding:10px 14px;border-radius:6px;margin-bottom:15px;}
label{display:block;margin-bottom:6px;font-weight:600;color:var(--text);}
input[type="text"], textarea, select{width:100%;padding:10px;margin-bottom:15px;border-radius:8px;border:1px solid #ccc;font-size:14px;}
button{padding:12px 25px;background:var(--accent);color:white;border:none;border-radius:8px;cursor:pointer;font-weight:600;}
button:hover{background:#004466;}
.controls{display:flex;align-items:center;gap:10px;}
#darkToggle{padding:8px 10px;border:none;border-radius:8px;background:rgba(255,255,255,0.3);color:white;cursor:pointer;}
@media(max-width:768px){.sidebar{transform:translateX(-280px);}.sidebar.active{transform:translateX(0);}.sidebar.active ~ .overlay{display:block;}.main{margin-left:0;padding:12px;}.hamburger{display:inline-block;}}
body.dark{--bg:#081014;--card-bg:rgba(255,255,255,0.05);--accent:#1fb6ff;--muted:#9aa6af;--text:#e6f2f6;--white:#0a0a0a;}
body.dark .sidebar{background:linear-gradient(180deg,#0b2b33,#072024);color:#bfeafc;}
body.dark .nav a{color:#bfeafc;}
body.dark .content h3{color:#1fb6ff;}
</style>
</head>
<body>
<div class="app">
	<aside class="sidebar" id="sidebar">
		<div class="logo"><img src="../assets/img/custora_logo.png" alt="Custora CRM"></div>
		<nav class="nav">
			<a href="../"><i class="fas fa-gauge"></i> Dashboard</a>
			<a href="../projects/"><i class="fas fa-diagram-project"></i> Manage Projects</a>
			<a href="../users/"><i class="fas fa-users-cog"></i> Manage Users</a>
			<a href="../issues/"><i class="fas fa-circle-exclamation"></i> All Issues</a>
			<a href="../profile/"><i class="fas fa-user"></i> My Profile</a>
			<a href="../../auth/logout.php" style="color:#b31b1b;"><i class="fas fa-sign-out-alt"></i> Logout</a>
		</nav>
		<div class="footer-note">&copy; <?= date('Y') ?> Digital Vortex Technologies</div>
	</aside>

	<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>

	<main class="main">
		<div class="header">
			<div class="header-left">
				<div class="hamburger" id="hamburger" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
				<span><strong><?= htmlspecialchars($username) ?></strong> (<?= htmlspecialchars($role) ?>)</span>
			</div>
			<div class="controls">
				<button id="darkToggle"><span id="darkLabel">Dark</span></button>
				<a href="../../auth/logout.php" style="color:white;text-decoration:none;"><i class="fas fa-sign-out-alt"></i> Logout</a>
			</div>
		</div>

		<div class="content" style="margin-top:20px;">
			<h3><i class="fas fa-edit"></i> Edit Project</h3>
			<?php if ($message): ?>
				<div class="message"><?= htmlspecialchars($message) ?></div>
			<?php endif; ?>

			<?php if ($project): ?>
			<form method="POST">
				<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">

				<label>Project Name:</label>
				<input type="text" name="name" value="<?= htmlspecialchars($project['name']) ?>" required>

				<label>Project Code:</label>
				<input type="text" name="code" value="<?= htmlspecialchars($project['code']) ?>" required>

				<label>Description:</label>
				<textarea name="description" rows="4" required><?= htmlspecialchars($project['description']) ?></textarea>

				<label>Status:</label>
				<select name="status">
					<option value="active" <?= $project['status'] === 'active' ? 'selected' : '' ?>>Active</option>
					<option value="archived" <?= $project['status'] === 'archived' ? 'selected' : '' ?>>Archived</option>
				</select>

				<button type="submit"><i class="fas fa-save"></i> Update Project</button>
			</form>
			<?php endif; ?>
		</div>
	</main>
</div>

<script>
function toggleSidebar() {
	const sidebar = document.getElementById('sidebar');
	const overlay = document.getElementById('overlay');
	sidebar.classList.toggle('active');
	overlay.style.display = sidebar.classList.contains('active') ? 'block' : 'none';
}

(function(){
	const body=document.body,toggle=document.getElementById('darkToggle'),label=document.getElementById('darkLabel');
	if(localStorage.getItem('custora_dark')==='1'){body.classList.add('dark');label.textContent='Light';}
	toggle.addEventListener('click',()=>{
		body.classList.toggle('dark');
		localStorage.setItem('custora_dark',body.classList.contains('dark')?'1':'0');
		label.textContent=body.classList.contains('dark')?'Light':'Dark';
	});
})();
</script>
</body>
</html>