<?php 
session_start();
if(!isset($_SESSION['username'])){
header("location: login.php");
}
else{
?>
<?php include("includes/header.php"); ?>
      <div id="content-wrapper">

        <div class="container-fluid">

          <ol class="breadcrumb">
            <li class="breadcrumb-item">
              <a href="index.html">Dashboard</a>
            </li>
            <li class="breadcrumb-item active">Edit Post</li>
          </ol>

          <h1>Edit Post</h1>
          <?php 
include("includes/db.php");

$id = intval($_GET['id']);
$res = $mysqli->query("SELECT * FROM n_2 WHERE id=$id");
$row = $res->fetch_assoc();

if(isset($_POST['update'])){
    $update_sql = [];

    foreach($_POST as $col => $val){
        if($col === 'update') continue; // تجاهل زرار التحديث
        $val = $mysqli->real_escape_string($val);
        $update_sql[] = "`$col`='".$val."'";
    }

    if(empty($update_sql)){
        echo "<script>alert('لا يوجد حقول للتحديث');</script>";
    } else {
        $sql = "UPDATE n_2 SET " . implode(", ", $update_sql) . " WHERE id=$id";
        if($mysqli->query($sql)){
            echo "<script>alert('تم التحديث بنجاح');window.location='index.php';</script>";
        } else {
            echo "<script>alert('خطأ: ".$mysqli->error."');</script>";
        }
    }
}



?>

<form method="post">
    <?php foreach($row as $col => $val){ 
        if($col == "id") continue; // مانعدلش الـ id
    ?>
        <label><?php echo $col; ?></label>
        <input class="form-control" type="text" name="<?php echo $col; ?>" value="<?php echo htmlspecialchars($val); ?>"><br>
    <?php } ?>
    <button type="submit" name="update">حفظ</button>
</form>

        </div>
<?php include("includes/footer.php"); }?>