<?php
/*
 * Copyright (c)  2006-2008 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* セッションを開始もしくは復元 */
session_start();

function create_customer($name, $zip, $address, $phone, $fax, $contact_person) {
  $id = sprintf("%04d", $_SESSION["customer_id_seq"]++);
  $customer = array(
    "id" => $id,
    "name" => $name,
    "zip" => $zip,
    "address" => $address,
    "phone" => $phone,
    "fax" => $fax,
    "contact_person" => $contact_person
  );

  $customers = find_all_customers();
  $customers[$id] = $customer;
  $_SESSION["customers"] = $customers;
  
  return $customer;
} 

function find_customer($id) {
  $customers = find_all_customers();
  return $customers[$id];
}

function find_all_customers() {
  if (isset($_SESSION["customers"])) {
    $customers = $_SESSION["customers"];
  } else {
    $customers = read_csv_file("data/fruitshop_customers.csv", "id");
    $_SESSION["customers"] = $customers; 
    $_SESSION["customer_id_seq"] = count($customers) + 1;
  }
  return $customers;
}

function find_product($id) {
  $products = find_all_products();
  return $products[$id];
}

function find_all_products() {
  if (isset($_SESSION["products"])) {
    $products = $_SESSION["products"];
  } else {
    $products = read_csv_file("data/fruitshop_products.csv", "id");
    $_SESSION["products"] = $products; 
  }
  return $products;
}

function create_order($customer_id, $details) {
  $total = 0;
  foreach ($details as $detail) {
    $product = find_product($detail["productId"]);
    $total += $product["unit_price"] * $detail["quantity"];
  }

  $order = array(
    "id" => sprintf("%s-%03d", date("Ymd"), $_SESSION["order_id_seq"]++),
    "customer_id" => $customer_id,
    "order_date" => date("Y/m/d"),
    "total" => $total 
  );

  $orders = find_all_orders();
  array_push($orders, $order);
  $_SESSION["orders"] = $orders;
  
  return $order;
} 

function find_all_orders() {
  if (isset($_SESSION["orders"])) {
    $orders = $_SESSION["orders"];
  } else {
    $orders = read_csv_file("data/fruitshop_orders.csv");
    $_SESSION["orders"] = $orders;
    $_SESSION["order_id_seq"] = count($orders) + 1;
  }
  return $orders;
}

function find_all_order_details() {
  if (isset($_SESSION["order_details"])) {
    $order_details = $_SESSION["order_details"];
  } else {
    $order_details = read_csv_file("data/fruitshop_order_details.csv");
    $_SESSION["order_details"] = $order_details;
  }
  return $order_details;
}
