from datetime import datetime
from django.shortcuts import render, redirect, reverse
from django.template import loader
from django.http import HttpResponse
from User.forms import MyForm,MyForm2,MyForm3,MyForm4
from django.contrib.auth import authenticate, login
from User import models as Umodels
from django.http import HttpResponseRedirect
from django.contrib import messages
import json

# -------------------   EF
import pandas as pd
import numpy as np
import math
import sklearn
import matplotlib.pyplot as plt
from datetime import datetime
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# -------------------   EF

# Demand Forecast
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA
from pandas.tseries.offsets import DateOffset

# Start  CompanyHome
def Homepage(request):
    return render(request, 'Admin/Homepage.html');
# End  CompanyHome



# Employee_Efficency
def Employee_Data(request):
    data1 = pd.read_csv('Data/WorkHistory.csv')
    data2 = pd.read_csv('Data/EmployeeStatus.csv')
    DateSet = pd.merge(data1, data2,  on='StaffID',   how='inner')
    grouped_df = DateSet.groupby("StaffID" )  # group job staff
    finalpt = grouped_df.head(10) # date from two datasets
    json_records = finalpt.reset_index().to_json(orient='records')
    arr = []
    arr = json.loads(json_records)
    context = {'d': arr}
    return render(request, 'Admin/Employee_Data.html',context);

def EmployeeStatus_Update(request):
    if request.method == 'POST':
        myForm = MyForm3(request.POST)
        if myForm.is_valid():
            StaffID = myForm.cleaned_data['StaffID']
            Availability = myForm.cleaned_data['Availability']
            DateSet = pd.read_csv("Data/EmployeeStatus.csv")
            StaffID = (int(StaffID) - 1)
            DateSet.at[StaffID,'Availability']= Availability
            DateSet.to_csv("Data/EmployeeStatus.csv", index=False)
            messages.success(request, 'Employee status successfully! Updated.')
            return HttpResponseRedirect(request.path_info)
        else:
            form = MyForm3()
            return render(request, 'Admin/EmployeeStatus_Update.html', {'form':form});

    else:
        form = MyForm3()
    return render(request, 'Admin/EmployeeStatus_Update.html', {'form':form});

# Demand Forecasting
def PurchaseHistory(request):
    data = pd.read_csv('Data/Purchasefile.csv')
    finalpt = data.head(10)
    json_records = finalpt.reset_index().to_json(orient='records')
    arr = []
    arr = json.loads(json_records)
    context = {'d': arr}
    return render(request, 'Admin/PurchaseHistory.html',context);



# start Admin ML
def Forecasting(request):
     if request.method == 'POST':
        myForm = MyForm4(request.POST)
        if myForm.is_valid():
            Productid = myForm.cleaned_data['Productid']
            inputdate = myForm.cleaned_data['inputdate']


            ProductName = "CALTEX Delo Gold Ultra"
            if (ProductName == "CALTEX Delo Gold Ultra"):  # load first product budget
                df = pd.read_csv('Data/Purchasefile.csv')
                df.head()

                df.columns = ["Month", "CALTEX Delo Gold Ultra", "Price1"]
                rrr = df.head()

                # Convert Month into Datetime
                df['Month'] = pd.to_datetime(df['Month'])
                df.set_index('Month', inplace=True)
                df.describe()

                test_result = adfuller(df['CALTEX Delo Gold Ultra'])
                test_result2 = adfuller(df['Price1'])

                def adfuller_test(Product1):
                    result = adfuller(Product1)
                    labels = ['ADF Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']
                    for value, label in zip(result, labels):
                        print(label + ' : ' + str(value))

                def adfuller_test2(Price1):
                    result2 = adfuller(Price1)
                    labels = ['ADF Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']
                    for value, label in zip(result2, labels):
                        print(label + ' : ' + str(value))

                adfuller_test(df['CALTEX Delo Gold Ultra'])
                adfuller_test2(df['Price1'])
                ##Differencing
                df['Product1 First Difference'] = df['CALTEX Delo Gold Ultra'] - df['CALTEX Delo Gold Ultra'].shift(1)
                df['Product1 First Difference2'] = df['Price1'] - df['Price1'].shift(1)
                #  df['Sales'].shift(1)
                df['Seasonal First Difference'] = df['CALTEX Delo Gold Ultra'] - df['CALTEX Delo Gold Ultra'].shift(12)
                df['Seasonal First Difference2'] = df['Price1'] - df['Price1'].shift(12)
                # df.head(14)

                ## Again test dickey fuller test
                adfuller_test(df['Seasonal First Difference'].dropna())
                adfuller_test2(df['Seasonal First Difference2'].dropna())

                # ARIMA
                model = ARIMA(df['CALTEX Delo Gold Ultra'], order=(1, 0, 0))
                model2 = ARIMA(df['Price1'], order=(1, 0, 0))
                model_fit = model.fit()
                model_fit2 = model2.fit()
                # model_fit.summary()
                df['forecast'] = model_fit.predict(start=104, end=120, dynamic=True)
                df['forecastPrice'] = model_fit2.predict(start=104, end=120, dynamic=True)
                # df[['Product1','forecast']].plot(figsize=(12,8))
                model = sm.tsa.statespace.SARIMAX(df['CALTEX Delo Gold Ultra'], order=(1, 1, 1),
                                                  seasonal_order=(1, 1, 1, 12))
                model2 = sm.tsa.statespace.SARIMAX(df['Price1'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))

                results = model.fit()
                results2 = model2.fit()

                future_dates = [df.index[-1] + DateOffset(months=x) for x in range(0, 150)]
                future_datest_df = pd.DataFrame(index=future_dates[1:], columns=df.columns)
                # future_datest_df.tail()
                future_df = pd.concat([df, future_datest_df])


                inputdatex = inputdate
                inputdate = datetime.strftime(inputdatex, "%m/%d/%Y")

                # 10/01/2025

                lastDate = '10/01/2021'

                inputdate = inputdate
                date_format = "%m/%d/%Y"
                a = datetime.strptime(lastDate, date_format)  # user input date
                b = datetime.strptime(inputdate, date_format)
                delta = b - a
                delta2 = delta.days
                # print(delta2)
                forcasting_date = int(delta2 / 30)
                newDate = forcasting_date + 121  # ending number

                #   print(forcasting_date)
                forecast = future_df['forecast'] = results.predict(start=119, end=newDate, dynamic=True)
                #    future_df[['Sales', 'forecast']].plot(figsize=(12, 8))

                forecastPrice = future_df['forecastPrice'] = results2.predict(start=119, end=newDate, dynamic=True)
                #   future_df[['Price1', 'forecastPrice']].plot(figsize=(12, 8))

                df3 = forecast[-1]
                df4 = forecastPrice[-1]

                PredictedDemand = int(df3)
                PredictedPrice = int(df4)
                PredictedBudget = PredictedDemand * PredictedPrice


                context = { 'arz': PredictedDemand , 'arz2': PredictedPrice , 'arz3': PredictedBudget , 'datagot': inputdate }
                template = loader.get_template('Admin/Result.html')
                return HttpResponse(template.render(context, request))
     else:
         form = MyForm4()
     #returning form
     return render(request, 'Admin/Forecasting.html', {'form':form});
# end Admin ML


def AdminLogin(request):
    if request.method == 'POST':
        myForm = MyForm2(request.POST)
        if myForm.is_valid():
            UserName = myForm.cleaned_data['UserName']
            Password = myForm.cleaned_data['Password']
            gotdata = Umodels.loginDataAdmin.objects.all().filter(UserName=UserName , Password=Password).count()
            if gotdata > 0:
                return render(request, 'Admin/AdminHome.html');
            else:
                messages.success(request, 'Login Info Not Found  , Please Check Your UserName and Password')
                return HttpResponseRedirect(request.path_info)
    else:
        form = MyForm2()
    return render(request, 'Admin/AdminLogin.html', {'form':form});


def AdminHome(request):
    return render(request,'Admin/AdminHome.html')




