<?php

class ItineraryEntryService {

    private $conn;
    private $table = "itinerary_entry";

    public function __construct($db) {
        $this->conn = $db;
    }

    public function add($itineraryEntry) {

        $query = "INSERT INTO " . $this->table . 
            " SET package = :package,
                day = :day,
                heading = :heading,
                hour = :hour,
                details = :details";
        
        $stmt = $this->conn->prepare($query);
        
        $itineraryEntry->day = htmlspecialchars(strip_tags($itineraryEntry->day));
        $itineraryEntry->heading = htmlspecialchars(strip_tags($itineraryEntry->heading));

        $stmt->bindParam(':package', $itineraryEntry->package);
        $stmt->bindParam(':day', $itineraryEntry->day);
        $stmt->bindParam(':heading', $itineraryEntry->heading);
        $stmt->bindParam(':hour', $itineraryEntry->hour);
        $stmt->bindParam(':details', $itineraryEntry->details);

        if($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    public function update($itineraryEntry) {

        $query = "UPDATE " . $this->table . 
            " SET package = :package,
                day = :day,
                heading = :heading,
                hour = :hour,
                details = :details
                WHERE id = :id";
        
        $stmt = $this->conn->prepare($query);
        
        $itineraryEntry->day = htmlspecialchars(strip_tags($itineraryEntry->day));
        $itineraryEntry->heading = htmlspecialchars(strip_tags($itineraryEntry->heading));

        $stmt->bindParam(':package', $itineraryEntry->package);
        $stmt->bindParam(':day', $itineraryEntry->day);
        $stmt->bindParam(':heading', $itineraryEntry->heading);
        $stmt->bindParam(':hour', $itineraryEntry->hour);
        $stmt->bindParam(':details', $itineraryEntry->details);
        $stmt->bindParam(':id', $itineraryEntry->id);

        if($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    public function listByPackage($package) {

        $query = "SELECT * FROM " . $this->table . 
            " WHERE package = :package ";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':package', $package);
        $stmt->execute();

        $result_list = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {       
            array_push($result_list, $row);
        }
        return $result_list;
    }

    public function itineraryExists($package) {

        $query = "SELECT * FROM " . $this->table . " WHERE package = :package";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':package', $package);
        $stmt->execute();

        $num_of_rows = $stmt->rowCount();
        
        if ($num_of_rows > 0) {
            return true;
        } else {
            return false;
        }
    }
}
?>