<?php
// Check if the user is logged in, if not then redirect to login page
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

// Include config file
require_once 'includes/config.php';

// Check if ID and status parameters exist
if(isset($_GET["id"]) && !empty(trim($_GET["id"])) && isset($_GET["status"]) && in_array($_GET["status"], ['new', 'read', 'replied'])){
    
    // Prepare an update statement
    $sql = "UPDATE contact_submissions SET status = ? WHERE id = ?";
    
    if($stmt = $conn->prepare($sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("si", $param_status, $param_id);
        
        // Set parameters
        $param_status = trim($_GET["status"]);
        $param_id = trim($_GET["id"]);
        
        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // Status updated successfully. Redirect to view contact page
            header("location: view_contact.php?id=" . $param_id);
            exit();
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }
    
    // Close statement
    $stmt->close();
    
    // Close connection
    $conn->close();
    
} else{
    // Invalid parameters. Redirect to error page
    header("location: error.php");
    exit();
}
?>
